use serde::{Deserialize, Serialize};
use super::error::AiError;
use super::format::Format;
#[cfg(feature = "kalosm")]
use kalosm_sample as _;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(
feature = "kalosm",
derive(kalosm::language::Parse, kalosm::language::Schema)
)]
pub struct Plan {
#[serde(default)]
pub ops: Vec<Op>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(
feature = "kalosm",
derive(kalosm::language::Parse, kalosm::language::Schema)
)]
#[serde(rename_all = "lowercase")]
pub enum Position {
Before,
#[default]
After,
Start,
End,
}
impl Position {
pub fn as_str(self) -> &'static str {
match self {
Self::Before => "before",
Self::After => "after",
Self::Start => "start",
Self::End => "end",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(
feature = "kalosm",
derive(kalosm::language::Parse, kalosm::language::Schema)
)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Op {
Replace {
index: u32,
old: String,
new: String,
},
Insert {
index: u32,
#[serde(default)]
position: Position,
text: String,
},
InsertParagraph {
index: u32,
#[serde(default)]
position: Position,
text: String,
},
Delete {
index: u32,
#[serde(default)]
text: String,
},
Comment {
index: u32,
#[serde(default)]
anchor: String,
text: String,
},
SetCell {
sheet: String,
cell: String,
value: String,
},
SetText {
slide: u32,
element: u32,
text: String,
},
}
impl Op {
pub fn name(&self) -> &'static str {
match self {
Self::Replace { .. } => "replace",
Self::Insert { .. } => "insert",
Self::InsertParagraph { .. } => "insert_paragraph",
Self::Delete { .. } => "delete",
Self::Comment { .. } => "comment",
Self::SetCell { .. } => "set_cell",
Self::SetText { .. } => "set_text",
}
}
pub fn format(&self) -> Format {
match self {
Self::Replace { .. }
| Self::Insert { .. }
| Self::InsertParagraph { .. }
| Self::Delete { .. }
| Self::Comment { .. } => Format::Docx,
Self::SetCell { .. } => Format::Xlsx,
Self::SetText { .. } => Format::Pptx,
}
}
pub(crate) fn require_format(&self, expected: Format) -> Result<(), AiError> {
let got = self.format();
if got == expected {
Ok(())
} else {
Err(AiError::Apply(format!(
"op {} is for {got}, but the file is {expected}",
self.name()
)))
}
}
}
pub trait Completer: Send + Sync {
fn complete(
&self,
view: &super::view::DocumentView,
instruction: &str,
) -> impl std::future::Future<Output = Result<Plan, AiError>> + Send;
}
#[derive(Debug, Clone)]
pub struct StaticCompleter {
plan: Plan,
}
impl StaticCompleter {
pub fn new(plan: Plan) -> Self {
Self { plan }
}
}
impl Completer for StaticCompleter {
async fn complete(
&self,
_view: &super::view::DocumentView,
_instruction: &str,
) -> Result<Plan, AiError> {
Ok(self.plan.clone())
}
}
pub fn system_prompt(format: Format) -> &'static str {
match format {
Format::Docx => {
"You edit a Word document by emitting operations against the numbered view. \
Copy `old` / `anchor` / `text` spans exactly from the view. Indexes are 1-based. \
Only emit ops the instruction requires. Prefer replace over delete+insert. \
DOCX ops become Word tracked changes a lawyer can accept or reject. \
Do not invent indexes. If nothing must change, emit an empty ops list."
}
Format::Xlsx => {
"You edit an Excel workbook by emitting set_cell operations. \
Each view line is `Sheet!A1<TAB>value`. Copy sheet names and A1 refs exactly. \
Only emit ops the instruction requires. Empty ops list if nothing must change."
}
Format::Pptx => {
"You edit a PowerPoint deck by emitting set_text operations. \
Each view line is `slide.element| text`. Slide and element are 1-based. \
Only emit ops the instruction requires. Empty ops list if nothing must change."
}
}
}
pub fn user_prompt(view: &super::view::DocumentView, instruction: &str) -> String {
format!("{}\n# Instruction\n{}", view.render(), instruction.trim())
}
#[cfg(test)]
mod tests {
use super::{system_prompt, user_prompt, Op, Plan};
#[test]
fn plan_round_trips_json() {
let plan = Plan {
ops: vec![Op::Replace {
index: 1,
old: "thirty".into(),
new: "sixty".into(),
}],
};
let json = serde_json::to_string(&plan).unwrap();
let back: Plan = serde_json::from_str(&json).unwrap();
assert_eq!(back.ops.len(), 1);
assert_eq!(back.ops[0].name(), "replace");
}
#[test]
fn prompts_name_the_format() {
use crate::ai::format::Format;
assert!(system_prompt(Format::Docx).contains("tracked"));
assert!(system_prompt(Format::Xlsx).contains("set_cell"));
assert!(system_prompt(Format::Pptx).contains("set_text"));
let view = crate::ai::view::DocumentView {
format: Format::Docx,
lines: vec!["1| hello".into()],
truncated: false,
};
let user = user_prompt(&view, "change hello");
assert!(user.contains("hello"));
assert!(user.contains("change hello"));
}
}