Files
leleka/desktop-core/examples/fake_runtime/pump.rs
T

117 lines
3.8 KiB
Rust

//! The generation pump of the fake runtime: engine output lines to generation events.
use std::{
io::{BufRead, BufReader},
process::Child,
sync::{Arc, Mutex},
time::Duration,
};
use leleka_backend_api as api;
use strata_control::{
reasoning_budget::Utf8Stream,
tokenizer::Tokenizer,
wire::{self, Event, Finish},
};
pub(super) struct Active {
pub(super) id: String,
}
/// The stand-in for leleka-inference *is* its engine: when the engine process dies, so does the
/// fake runtime, as the real one would take its engine down with it.
pub(super) fn exit_with_the_engine(watched: Arc<Mutex<Child>>) {
std::thread::spawn(move || {
loop {
std::thread::sleep(Duration::from_millis(50));
if let Ok(Some(status)) = watched.lock().unwrap().try_wait() {
eprintln!("fake_runtime: the engine exited ({status}); exiting");
std::process::exit(2);
}
}
});
}
/// Turns the engine's output lines into generation events until a terminal event or an error.
pub(super) struct Pump {
pub(super) tokenizer: Arc<Tokenizer>,
pub(super) active: Arc<Mutex<Option<Active>>>,
pub(super) sink: api::GenerationSink,
pub(super) utf8: Utf8Stream,
}
impl Pump {
pub(super) fn run(mut self, lines: Arc<Mutex<BufReader<std::process::ChildStdout>>>) {
let stops = ["<|im_end|>", "<|endoftext|>"].map(|s| self.tokenizer.special_id(s));
let mut reader = lines.lock().unwrap();
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
self.release();
return; // the engine died: no terminal event
}
let finished = match wire::parse_line(&line) {
Ok(Some(Event::Token(id))) => self.token(id, &stops),
Ok(Some(Event::Done(done))) => self.done(done),
Ok(Some(Event::Error(message))) => {
self.release();
let _ = self.sink.fail(api::ErrorCode::Internal, message, false);
true
}
Ok(Some(Event::PromptProgress { .. }) | None) => false,
Err(_) => {
self.release();
true
}
};
if finished {
return;
}
}
}
fn release(&self) {
*self.active.lock().unwrap() = None;
}
/// Forwards one token as text; true when the consumer is gone.
fn token(&mut self, id: u32, stops: &[Option<u32>]) -> bool {
if stops.contains(&Some(id)) {
return false; // the Rust engine never reports its stop token
}
let bytes = self.tokenizer.decode_bytes(&[id]).unwrap_or_default();
let text = self.utf8.push(&bytes);
if !text.is_empty()
&& self
.sink
.emit(api::GenerationEvent::TextDelta { text })
.is_err()
{
self.release();
return true;
}
false
}
fn done(&mut self, done: wire::Done) -> bool {
let tail = self.utf8.push(&[]);
if !tail.is_empty() {
let _ = self
.sink
.emit(api::GenerationEvent::TextDelta { text: tail });
}
self.release();
let usage = api::Usage {
input_tokens: done.prompt_tokens,
output_tokens: done.generated,
reused_input_tokens: done.reused.unwrap_or(0),
};
let _ = match done.finish {
Finish::Stop => self.sink.complete(api::FinishReason::Stop, usage),
Finish::Length => self.sink.complete(api::FinishReason::Length, usage),
Finish::Cancel => self.sink.cancel(),
};
true
}
}