Files
leleka/crates/harmony/src/parse.rs
T

244 lines
7.8 KiB
Rust

//! Parsing the messages a gpt-oss model generates.
//!
//! The model continues a prompt that ends in `<|start|>assistant` and writes messages of the form
//! `<|channel|>NAME [to=RECIPIENT] [<|constrain|>TYPE]<|message|>BODY` closed by `<|end|>` (more
//! messages follow), `<|return|>` (the final answer is complete) or `<|call|>` (a tool call is complete).
//! Messages after the first begin with `<|start|>assistant`. The parser consumes the generated stream
//! as text pieces and special markers, and returns events: reasoning text, answer text, and tool calls
//! with their arguments streamed in order.
use std::mem;
/// A special marker of the format.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Special {
Start,
End,
Message,
Channel,
Constrain,
Return,
Call,
/// Any other control token (end of text, reserved ids); ignored by the parser.
Other,
}
impl Special {
/// The marker for the text of a special token.
pub fn from_token_text(text: &str) -> Self {
match text {
"<|start|>" => Self::Start,
"<|end|>" => Self::End,
"<|message|>" => Self::Message,
"<|channel|>" => Self::Channel,
"<|constrain|>" => Self::Constrain,
"<|return|>" => Self::Return,
"<|call|>" => Self::Call,
_ => Self::Other,
}
}
}
/// One item of the generated stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Piece<'a> {
Special(Special),
Text(&'a str),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Event {
/// Text of the analysis channel (the model's reasoning).
Reasoning(String),
/// Text meant for the user (final channel, and commentary without a recipient).
Content(String),
/// A tool call began; `name` is the function name (the text after `functions.`), or the whole
/// recipient for any other namespace. `index` counts the tool calls of this generation.
ToolCallStart { index: u32, name: String },
/// A piece of the arguments of the current tool call.
ToolCallArguments(String),
/// The current tool call's arguments are complete.
ToolCallEnd,
/// `<|return|>` arrived: the answer is complete.
Returned,
/// `<|call|>` arrived: the model waits for the tool results.
Called,
}
#[derive(Debug, Eq, PartialEq)]
enum Mode {
/// Between messages (before the first, or after `<|end|>`).
Idle,
/// Reading a header; `text` collects what lies between the markers.
Header,
Body(Body),
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum Body {
Reasoning,
Content,
Tool,
/// A channel the parser does not know: its text is dropped.
Ignored,
}
pub struct HarmonyParser {
mode: Mode,
/// Header text since the last marker, and what the markers before it said.
header: String,
channel: Option<String>,
recipient: Option<String>,
tool_calls: u32,
}
impl Default for HarmonyParser {
fn default() -> Self {
Self::new()
}
}
impl HarmonyParser {
/// A parser for a generation that continues `<|start|>assistant`.
pub fn new() -> Self {
Self {
// the prompt already holds `<|start|>assistant`, so the first marker is `<|channel|>`
mode: Mode::Header,
header: String::new(),
channel: None,
recipient: None,
tool_calls: 0,
}
}
fn reset_header(&mut self) {
self.header.clear();
self.channel = None;
self.recipient = None;
}
/// Fold the pending header text into the channel and recipient.
fn absorb_header(&mut self, after_channel: bool) {
let text = mem::take(&mut self.header);
let mut words = text.split_whitespace().peekable();
if after_channel && self.channel.is_none() {
self.channel = words.next().map(str::to_owned);
}
for word in words {
if let Some(recipient) = word.strip_prefix("to=") {
self.recipient = Some(recipient.to_owned());
}
}
}
pub fn push(&mut self, piece: Piece) -> Vec<Event> {
let mut events = Vec::new();
match piece {
Piece::Text(text) => self.push_text(text, &mut events),
Piece::Special(special) => self.push_special(special, &mut events),
}
events
}
fn push_text(&mut self, text: &str, events: &mut Vec<Event>) {
match &self.mode {
Mode::Header => self.header.push_str(text),
Mode::Body(Body::Reasoning) => events.push(Event::Reasoning(text.to_owned())),
Mode::Body(Body::Content) => events.push(Event::Content(text.to_owned())),
Mode::Body(Body::Tool) => events.push(Event::ToolCallArguments(text.to_owned())),
Mode::Body(Body::Ignored) | Mode::Idle => {}
}
}
fn push_special(&mut self, special: Special, events: &mut Vec<Event>) {
match special {
Special::Start => {
self.close_message(events);
self.reset_header();
self.mode = Mode::Header;
}
Special::Channel => self.begin_channel(),
Special::Constrain => {
if self.mode == Mode::Header {
self.absorb_header(true);
}
}
Special::Message => self.begin_body(events),
Special::End => {
self.close_message(events);
self.mode = Mode::Idle;
}
Special::Call => self.end_generation_part(events, Event::Called),
Special::Return => self.end_generation_part(events, Event::Returned),
Special::Other => {}
}
}
fn begin_channel(&mut self) {
// the text before the marker (a role, or a recipient written after the start) is
// not the channel name; the text after it is
if self.mode == Mode::Header {
self.absorb_header(false);
self.channel = None;
self.mode = Mode::Header;
}
}
fn begin_body(&mut self, events: &mut Vec<Event>) {
if self.mode == Mode::Header {
self.absorb_header(true);
let body = self.start_body(events);
self.mode = Mode::Body(body);
}
}
fn end_generation_part(&mut self, events: &mut Vec<Event>, last: Event) {
self.close_message(events);
events.push(last);
self.mode = Mode::Idle;
}
/// Decide what the message body is from the header just read.
fn start_body(&mut self, events: &mut Vec<Event>) -> Body {
let channel = self.channel.clone().unwrap_or_default();
let recipient = self.recipient.take();
self.reset_header();
match (channel.as_str(), recipient) {
(_, Some(recipient)) if recipient != "assistant" && recipient != "user" => {
let name = recipient
.strip_prefix("functions.")
.unwrap_or(&recipient)
.to_owned();
events.push(Event::ToolCallStart {
index: self.tool_calls,
name,
});
self.tool_calls += 1;
Body::Tool
}
("analysis", _) => Body::Reasoning,
("final", _) | ("commentary", _) => Body::Content,
_ => Body::Ignored,
}
}
fn close_message(&mut self, events: &mut Vec<Event>) {
if self.mode == Mode::Body(Body::Tool) {
events.push(Event::ToolCallEnd);
}
self.reset_header();
}
/// The stream ended (length limit, cancellation, end of text). Closes an open tool call so the
/// consumer sees a matching end.
pub fn finish(&mut self) -> Vec<Event> {
let mut events = Vec::new();
self.close_message(&mut events);
self.mode = Mode::Idle;
events
}
}
#[cfg(test)]
mod tests;