use core::fmt;
pub const EVENT_SLOT: &str = "{{event}}";
pub const IMAGE_SLOT: &str = "{{image_path}}";
pub const CONTEXT_COMMAND_SLOT: &str = "{{context_command}}";
pub const SLOTS: [&str; 3] = [EVENT_SLOT, IMAGE_SLOT, CONTEXT_COMMAND_SLOT];
pub const NO_IMAGE: &str = "(this event arrived with no image)";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TemplateError {
SlotMissing {
slot: &'static str,
},
SlotRepeated {
slot: &'static str,
},
}
impl fmt::Display for TemplateError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SlotMissing { slot } => {
write!(formatter, "the prompt template declares no {slot} slot")
}
Self::SlotRepeated { slot } => {
write!(
formatter,
"the prompt template declares {slot} more than once"
)
}
}
}
}
impl core::error::Error for TemplateError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PromptTemplate {
segments: Vec<String>,
order: Vec<&'static str>,
}
impl PromptTemplate {
pub fn parse(text: &str) -> Result<Self, TemplateError> {
let mut positions: Vec<(usize, &'static str)> = Vec::with_capacity(SLOTS.len());
for slot in SLOTS {
let mut found = text.match_indices(slot);
let Some((at, _)) = found.next() else {
return Err(TemplateError::SlotMissing { slot });
};
if found.next().is_some() {
return Err(TemplateError::SlotRepeated { slot });
}
positions.push((at, slot));
}
positions.sort_unstable();
let mut segments = Vec::with_capacity(positions.len() + 1);
let mut order = Vec::with_capacity(positions.len());
let mut cursor = 0;
for (at, slot) in positions {
segments.push(text[cursor..at].to_owned());
order.push(slot);
cursor = at + slot.len();
}
segments.push(text[cursor..].to_owned());
Ok(Self { segments, order })
}
#[must_use]
pub fn fill(&self, event: &str, image_path: &str, context_command: &str) -> String {
let mut filled = String::new();
for (index, segment) in self.segments.iter().enumerate() {
filled.push_str(segment);
match self.order.get(index) {
Some(&EVENT_SLOT) => filled.push_str(event),
Some(&IMAGE_SLOT) => filled.push_str(image_path),
Some(&CONTEXT_COMMAND_SLOT) => filled.push_str(context_command),
Some(_) | None => {}
}
}
filled
}
}