use ai_api::{Flow, OnReply, OnThink, clean_text as clean};
use crossfire::{MTx, mpsc::List};
use crate::event::Event;
pub struct Job {
tx: MTx<List<Event>>,
id: u32,
ended: bool,
}
impl Job {
pub(crate) fn new(tx: MTx<List<Event>>, id: u32) -> Self {
Self {
tx,
id,
ended: false,
}
}
fn end(&mut self, err: Option<String>) {
self.ended = true;
let _ = self.tx.send(Event::End { id: self.id, err });
}
pub fn reply(&self) -> Reply {
Reply {
tx: self.tx.clone(),
id: self.id,
}
}
pub fn done(mut self) {
self.end(None);
}
pub fn fail(mut self, err: &str) {
self.end(Some(clean(err).into_owned()));
}
}
pub struct Reply {
tx: MTx<List<Event>>,
id: u32,
}
fn text(tx: &MTx<List<Event>>, id: u32, s: &str, reply: bool) -> Flow {
let _ = tx.send(Event::Text {
id,
text: clean(s).into_owned(),
reply,
});
Flow::Continue
}
impl OnThink for Job {
fn think(&mut self, s: &str) -> Flow {
text(&self.tx, self.id, s, false)
}
}
impl OnReply for Reply {
fn reply(&mut self, s: &str) -> Flow {
text(&self.tx, self.id, s, true)
}
}
impl Drop for Job {
fn drop(&mut self) {
if !self.ended {
self.end(Some("已取消".into()));
}
}
}