Skip to main content

synaptic_parsers/
enum_parser.rs

1use async_trait::async_trait;
2use synaptic_core::{RunnableConfig, SynapticError};
3use synaptic_runnables::Runnable;
4
5use crate::FormatInstructions;
6
7/// Validates that the trimmed input matches one of the allowed enum values.
8pub struct EnumOutputParser {
9    allowed: Vec<String>,
10}
11
12impl EnumOutputParser {
13    pub fn new(allowed: Vec<String>) -> Self {
14        Self { allowed }
15    }
16}
17
18impl FormatInstructions for EnumOutputParser {
19    fn get_format_instructions(&self) -> String {
20        let values = self.allowed.join(", ");
21        format!("Your response should be one of the following values: {values}")
22    }
23}
24
25#[async_trait]
26impl Runnable<String, String> for EnumOutputParser {
27    async fn invoke(
28        &self,
29        input: String,
30        _config: &RunnableConfig,
31    ) -> Result<String, SynapticError> {
32        let trimmed = input.trim().to_string();
33        if self.allowed.contains(&trimmed) {
34            Ok(trimmed)
35        } else {
36            Err(SynapticError::Parsing(format!(
37                "expected one of {:?}, got '{trimmed}'",
38                self.allowed
39            )))
40        }
41    }
42}