Skip to main content

synaptic_parsers/
markdown_list_parser.rs

1use async_trait::async_trait;
2use synaptic_core::{RunnableConfig, SynapticError};
3use synaptic_runnables::Runnable;
4
5use crate::FormatInstructions;
6
7/// Parses markdown-formatted lists (both `- item` and `* item`).
8pub struct MarkdownListOutputParser;
9
10impl FormatInstructions for MarkdownListOutputParser {
11    fn get_format_instructions(&self) -> String {
12        "Your response should be a markdown list using `- ` or `* ` for each item.".to_string()
13    }
14}
15
16#[async_trait]
17impl Runnable<String, Vec<String>> for MarkdownListOutputParser {
18    async fn invoke(
19        &self,
20        input: String,
21        _config: &RunnableConfig,
22    ) -> Result<Vec<String>, SynapticError> {
23        let items: Vec<String> = input
24            .lines()
25            .filter_map(|line| {
26                let trimmed = line.trim_start();
27                if let Some(rest) = trimmed.strip_prefix("- ") {
28                    let item = rest.trim().to_string();
29                    if item.is_empty() {
30                        None
31                    } else {
32                        Some(item)
33                    }
34                } else if let Some(rest) = trimmed.strip_prefix("* ") {
35                    let item = rest.trim().to_string();
36                    if item.is_empty() {
37                        None
38                    } else {
39                        Some(item)
40                    }
41                } else {
42                    None
43                }
44            })
45            .collect();
46
47        Ok(items)
48    }
49}