askit-std-agents 0.9.0

Standard Agents of Agent Stream Kit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use agent_stream_kit::{
    ASKit, Agent, AgentContext, AgentData, AgentError, AgentOutput, AgentSpec, AgentValue, AsAgent,
    askit_agent, async_trait,
};
use handlebars::Handlebars;
use im::vector;
use serde_json::json;

const CATEGORY: &str = "Std/String";

const PIN_STRING: &str = "string";
const PIN_STRINGS: &str = "strings";
const PIN_VALUE: &str = "value";
const PIN_T: &str = "t";
const PIN_F: &str = "f";

const CONFIG_LEN: &str = "len";
const CONFIG_OVERLAP: &str = "overlap";
const CONFIG_SEP: &str = "sep";
const CONFIG_TEMPLATE: &str = "template";

/// Check if the input is a string.
#[askit_agent(
    title = "IsString",
    category = CATEGORY,
    inputs = [PIN_VALUE],
    outputs = [PIN_T, PIN_F],
)]
struct IsStringAgent {
    data: AgentData,
}

#[async_trait]
impl AsAgent for IsStringAgent {
    fn new(askit: ASKit, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
        Ok(Self {
            data: AgentData::new(askit, id, spec),
        })
    }

    async fn process(
        &mut self,
        ctx: AgentContext,
        _pin: String,
        value: AgentValue,
    ) -> Result<(), AgentError> {
        if value.is_string() {
            self.output(ctx, PIN_T, value).await
        } else {
            self.output(ctx, PIN_F, value).await
        }
    }
}

/// Check if the input string is empty.
#[askit_agent(
    title = "IsEmptyString",
    category = CATEGORY,
    inputs = [PIN_STRING],
    outputs = [PIN_T, PIN_F],
)]
struct IsEmptyStringAgent {
    data: AgentData,
}

#[async_trait]
impl AsAgent for IsEmptyStringAgent {
    fn new(askit: ASKit, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
        Ok(Self {
            data: AgentData::new(askit, id, spec),
        })
    }

    async fn process(
        &mut self,
        ctx: AgentContext,
        _pin: String,
        value: AgentValue,
    ) -> Result<(), AgentError> {
        let is_empty = if let Some(s) = value.as_str() {
            s.is_empty()
        } else {
            false
        };
        if is_empty {
            self.output(ctx, PIN_T, value).await
        } else {
            self.output(ctx, PIN_F, value).await
        }
    }
}

/// The `StringJoinAgent` is responsible for joining an array of strings into a single string
/// using a specified separator. It processes input value, applies transformations to handle
/// escape sequences (e.g., `\n`, `\t`), and outputs the resulting string.
///
/// # Configuration
/// - `CONFIG_SEP`: Specifies the separator to use when joining strings. Defaults to an empty string.
///
/// # Input
/// - Expects an array of strings as input value.
///
/// # Output
/// - Produces a single joined string as output.
///
/// # Example
/// Given the input `["Hello", "World"]` and `CONFIG_SEP` set to `" "`, the output will be `"Hello World"`.
#[askit_agent(
    title = "String Join",
    category = CATEGORY,
    inputs = [PIN_STRINGS],
    outputs = [PIN_STRING],
    string_config(name = CONFIG_SEP, default = "\\n")
)]
struct StringJoinAgent {
    data: AgentData,
}

#[async_trait]
impl AsAgent for StringJoinAgent {
    fn new(askit: ASKit, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
        Ok(Self {
            data: AgentData::new(askit, id, spec),
        })
    }

    async fn process(
        &mut self,
        ctx: AgentContext,
        _pin: String,
        value: AgentValue,
    ) -> Result<(), AgentError> {
        let config = self.configs()?;

        let sep = config.get_string_or_default(CONFIG_SEP);

        if value.is_array() {
            let mut out = Vec::new();
            for v in value
                .as_array()
                .ok_or_else(|| AgentError::InvalidArrayValue("Expected array".into()))?
            {
                out.push(v.as_str().unwrap_or_default());
            }
            let mut out = out.join(&sep);
            out = out.replace("\\n", "\n");
            out = out.replace("\\t", "\t");
            out = out.replace("\\r", "\r");
            out = out.replace("\\\\", "\\");
            let out_value = AgentValue::string(out);
            self.output(ctx, PIN_STRING, out_value).await
        } else {
            self.output(ctx, PIN_STRING, value).await
        }
    }
}

#[askit_agent(
    title = "String Length Split",
    category = CATEGORY,
    inputs = [PIN_STRING],
    outputs = [PIN_STRINGS],
    integer_config(name = CONFIG_LEN, default = 65536),
    integer_config(name = CONFIG_OVERLAP, default = 1024),
)]
struct StringLengthSplitAgent {
    data: AgentData,
}

#[async_trait]
impl AsAgent for StringLengthSplitAgent {
    fn new(askit: ASKit, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
        Ok(Self {
            data: AgentData::new(askit, id, spec),
        })
    }

    async fn process(
        &mut self,
        ctx: AgentContext,
        _pin: String,
        value: AgentValue,
    ) -> Result<(), AgentError> {
        let config = self.configs()?;

        let n = config.get_integer_or_default(CONFIG_LEN) as usize;
        if n <= 0 {
            return Err(AgentError::InvalidConfig("n must be greater than 0".into()));
        }

        let overlap = config.get_integer_or_default(CONFIG_OVERLAP) as usize;
        if overlap >= n {
            return Err(AgentError::InvalidConfig(
                "overlap must be less than n".into(),
            ));
        }

        let s = value
            .as_str()
            .ok_or_else(|| AgentError::InvalidValue("Input value must be a string".into()))?;

        let mut out = Vec::new();
        let mut start = 0;
        let len = s.len();
        while start < len {
            let mut end = usize::min(start + n, len);
            while !s.is_char_boundary(end) {
                end -= 1;
            }
            if end <= start {
                end = start + s[start..].chars().next().map(|c| c.len_utf8()).unwrap_or(1);
            }

            out.push(AgentValue::string(s[start..end].to_string()));

            if end == len {
                break;
            }

            let mut next_start = end.saturating_sub(overlap);
            while next_start < len && !s.is_char_boundary(next_start) {
                next_start += 1;
            }
            start = next_start;
        }
        self.output(ctx, PIN_STRINGS, AgentValue::array(out.into()))
            .await
    }
}

// Template String Agent
#[askit_agent(
    title = "Template String",
    category = CATEGORY,
    inputs = [PIN_VALUE],
    outputs = [PIN_STRING],
    string_config(name = CONFIG_TEMPLATE, default = "{{value}}")
)]
struct TemplateStringAgent {
    data: AgentData,
}

#[async_trait]
impl AsAgent for TemplateStringAgent {
    fn new(askit: ASKit, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
        Ok(Self {
            data: AgentData::new(askit, id, spec),
        })
    }

    async fn process(
        &mut self,
        ctx: AgentContext,
        _pin: String,
        value: AgentValue,
    ) -> Result<(), AgentError> {
        let config = self.configs()?;

        let template = config.get_string_or_default(CONFIG_TEMPLATE);
        if template.is_empty() {
            return Err(AgentError::InvalidConfig("template is not set".into()));
        }

        let reg = handlebars_new();

        if value.is_array() {
            let mut out_arr = Vec::new();
            for v in value
                .as_array()
                .ok_or_else(|| AgentError::InvalidArrayValue("Expected array".into()))?
            {
                let data = json!({"value": v});
                let rendered_string = reg.render_template(&template, &data).map_err(|e| {
                    AgentError::InvalidValue(format!("Failed to render template: {}", e))
                })?;
                out_arr.push(rendered_string.into());
            }
            self.output(ctx, PIN_STRING, AgentValue::array(out_arr.into()))
                .await
        } else {
            let data = json!({"value": value});
            let rendered_string = reg.render_template(&template, &data).map_err(|e| {
                AgentError::InvalidValue(format!("Failed to render template: {}", e))
            })?;
            let out_value = AgentValue::string(rendered_string);
            self.output(ctx, PIN_STRING, out_value).await
        }
    }
}

// Template Text Agent
#[askit_agent(
    title = "Template Text",
    category = CATEGORY,
    inputs = [PIN_VALUE],
    outputs = [PIN_STRING],
    text_config(name = CONFIG_TEMPLATE, default = "{{value}}")
)]
struct TemplateTextAgent {
    data: AgentData,
}

#[async_trait]
impl AsAgent for TemplateTextAgent {
    fn new(askit: ASKit, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
        Ok(Self {
            data: AgentData::new(askit, id, spec),
        })
    }

    async fn process(
        &mut self,
        ctx: AgentContext,
        _pin: String,
        value: AgentValue,
    ) -> Result<(), AgentError> {
        let config = self.configs()?;

        let template = config.get_string_or_default(CONFIG_TEMPLATE);
        if template.is_empty() {
            return Err(AgentError::InvalidConfig("template is not set".into()));
        }

        let reg = handlebars_new();

        if value.is_array() {
            let mut out_arr = Vec::new();
            for v in value
                .as_array()
                .ok_or_else(|| AgentError::InvalidArrayValue("Expected array".into()))?
            {
                let data = json!({"value": v});
                let rendered_string = reg.render_template(&template, &data).map_err(|e| {
                    AgentError::InvalidValue(format!("Failed to render template: {}", e))
                })?;
                out_arr.push(rendered_string.into());
            }
            self.output(ctx, PIN_STRING, AgentValue::array(out_arr.into()))
                .await
        } else {
            let data = json!({"value": value});
            let rendered_string = reg.render_template(&template, &data).map_err(|e| {
                AgentError::InvalidValue(format!("Failed to render template: {}", e))
            })?;
            let out_value = AgentValue::string(rendered_string);
            self.output(ctx, PIN_STRING, out_value).await
        }
    }
}

// Template Array Agent
#[askit_agent(
    title = "Template Array",
    category = CATEGORY,
    inputs = [PIN_VALUE],
    outputs = [PIN_STRING],
    text_config(name = CONFIG_TEMPLATE, default = "{{value}}")
)]
struct TemplateArrayAgent {
    data: AgentData,
}

#[async_trait]
impl AsAgent for TemplateArrayAgent {
    fn new(askit: ASKit, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
        Ok(Self {
            data: AgentData::new(askit, id, spec),
        })
    }

    async fn process(
        &mut self,
        ctx: AgentContext,
        _pin: String,
        value: AgentValue,
    ) -> Result<(), AgentError> {
        let config = self.configs()?;

        let template = config.get_string_or_default(CONFIG_TEMPLATE);
        if template.is_empty() {
            return Err(AgentError::InvalidConfig("template is not set".into()));
        }

        let reg = handlebars_new();

        if value.is_array() {
            let rendered_string = reg.render_template(&template, &value).map_err(|e| {
                AgentError::InvalidValue(format!("Failed to render template: {}", e))
            })?;
            self.output(ctx, PIN_STRING, AgentValue::string(rendered_string))
                .await
        } else {
            let d = AgentValue::array(vector![value.clone()]);
            let rendered_string = reg.render_template(&template, &d).map_err(|e| {
                AgentError::InvalidValue(format!("Failed to render template: {}", e))
            })?;
            let out_value = AgentValue::string(rendered_string);
            self.output(ctx, PIN_STRING, out_value).await
        }
    }
}

fn handlebars_new<'a>() -> Handlebars<'a> {
    let mut reg = Handlebars::new();
    reg.register_escape_fn(handlebars::no_escape);
    reg.register_helper("to_json", Box::new(to_json_helper));

    #[cfg(feature = "yaml")]
    reg.register_helper("to_yaml", Box::new(to_yaml_helper));

    reg
}

fn to_json_helper(
    h: &handlebars::Helper<'_>,
    _: &handlebars::Handlebars<'_>,
    _: &handlebars::Context,
    _: &mut handlebars::RenderContext<'_, '_>,
    out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
    if let Some(value) = h.param(0) {
        let json_str = serde_json::to_string_pretty(&value.value()).map_err(|e| {
            handlebars::RenderErrorReason::Other(format!("Failed to serialize to JSON: {}", e))
        })?;
        out.write(&json_str)?;
    }
    Ok(())
}

#[cfg(feature = "yaml")]
fn to_yaml_helper(
    h: &handlebars::Helper<'_>,
    _: &handlebars::Handlebars<'_>,
    _: &handlebars::Context,
    _: &mut handlebars::RenderContext<'_, '_>,
    out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
    if let Some(value) = h.param(0) {
        let yaml_str = serde_yaml_ng::to_string(&value.value()).map_err(|e| {
            handlebars::RenderErrorReason::Other(format!("Failed to serialize to YAML: {}", e))
        })?;
        out.write(&yaml_str)?;
    }
    Ok(())
}