STRA-338 S23: OutputEvent and per-family OutputDecoder in leleka-gateway-domain; the plain-text stream reads events

New pure module leleka-gateway-domain::output: OutputEvent (reasoning delta, reasoning, text, whole tool call),
OutputError (decode / parse), OutputDecoder (an enum over the families: Qwen3.5 tokenizer bytes, the Harmony decoder),
a live reading (text and tool calls as bytes arrive) and a reading at the end (reasoning split on </think>, batch parse
of the answer, the unclosed-reasoning rules, reasoning token count), and output_items (events to response items).
The Harmony decoder moved from control-plane/src/harmony_family.rs unchanged (it still writes the Qwen-style markup
the readers parse); TextCodec gets output_decoder(plan). The readers are ports of the code in stream/ and tool_calls.rs.

Migrated site: responses/stream/text.rs (plain-text stream) now takes OutputEvent::Text from the decoder instead of
draining UTF-8 itself. Proof: output_golden (132 captures) identical, strata-control and gateway-domain lib tests
pass, check-limits / check-architecture / check-ci-coverage green, 0 new warnings.
This commit is contained in:
Pavlo Ratushnyi
2026-11-06 20:56:04 +01:00
parent 08afbf2160
commit eb003147a6
14 changed files with 1081 additions and 226 deletions
+9 -208
View File
@@ -1,18 +1,12 @@
//! The gpt-oss model family: its tokenizer and the decoder that turns Harmony output into the markup
//! the Responses code already understands.
//!
//! The generation is a sequence of Harmony messages (analysis, commentary, final). The decoder
//! translates it into the Qwen-style text the existing code parses: the reasoning text first (the
//! output is taken to start inside a `<think>` block, as for Qwen), then `</think>`, then the answer
//! text and one `<tool_call>` block per function call. That keeps the validation of tool names and
//! arguments, the history, and the streaming events in one place.
//! The gpt-oss model family: its tokenizer. The decoder that turns Harmony output into output events is
//! `leleka_gateway_domain::output::HarmonyDecoder` (see there for the format it reads).
use std::path::Path;
use std::sync::Arc;
use leleka_harmony::{Event, HarmonyParser, Piece, SENTINELS, Special};
use leleka_tokenizer::gguf_bpe::{GgufBpe, Utf8Stream};
use serde_json::Value;
use leleka_gateway_domain::output::{HarmonyDecoder, OutputDecoder, ReadPlan};
use leleka_harmony::SENTINELS;
use leleka_tokenizer::gguf_bpe::GgufBpe;
use crate::codec::{Family, TextCodec, TokenDecoder};
@@ -93,207 +87,14 @@ impl TextCodec for GptOssCodec {
Box::new(HarmonyDecoder::new(self.bpe.clone()))
}
fn output_decoder<'a>(&self, plan: ReadPlan<'a>) -> OutputDecoder<'a> {
OutputDecoder::harmony(HarmonyDecoder::new(self.bpe.clone()), plan)
}
fn terminal_ids(&self) -> Vec<u32> {
self.terminal.clone()
}
}
/// The tool call being collected: its name and the argument text received so far.
struct OpenCall {
name: String,
arguments: String,
}
/// Translates the generated Harmony token stream to Qwen-style markup, token by token.
pub struct HarmonyDecoder {
bpe: Arc<GgufBpe>,
parser: HarmonyParser,
utf8: Utf8Stream,
/// Output so far is still inside the (virtual) `<think>` block.
thinking: bool,
/// Some answer text or tool call has been written.
answered: bool,
/// An analysis message ended without any answer after it.
reasoning_closed: bool,
/// The previous message ended: separate the next answer text from the last one.
message_break: bool,
call: Option<OpenCall>,
}
impl HarmonyDecoder {
pub fn new(bpe: Arc<GgufBpe>) -> Self {
Self {
bpe,
parser: HarmonyParser::new(),
utf8: Utf8Stream::default(),
thinking: true,
answered: false,
reasoning_closed: false,
message_break: false,
call: None,
}
}
fn close_thinking(&mut self, out: &mut String) {
if self.thinking {
out.push_str("</think>\n\n");
self.thinking = false;
}
}
/// Answer text: after a message break the next answer is separated by a blank line.
fn content(&mut self, text: &str, out: &mut String) {
self.close_thinking(out);
if self.answered && self.message_break {
out.push_str("\n\n");
}
self.answered = true;
self.message_break = false;
out.push_str(text);
}
/// A tool call opens: separated from earlier answer text by a blank line.
fn start_call(&mut self, name: String, out: &mut String) {
self.close_thinking(out);
if self.answered {
out.push_str("\n\n");
}
self.answered = true;
self.message_break = false;
self.call = Some(OpenCall {
name,
arguments: String::new(),
});
}
fn translate(&mut self, events: Vec<Event>, out: &mut String) -> Result<(), String> {
for event in events {
match event {
Event::Reasoning(text) => {
// reasoning after the answer started has nowhere to go; it is hidden anyway
if self.thinking {
out.push_str(&text);
}
}
Event::Content(text) => self.content(&text, out),
Event::ToolCallStart { name, .. } => self.start_call(name, out),
Event::ToolCallArguments(text) => {
if let Some(call) = &mut self.call {
call.arguments.push_str(&text);
}
}
Event::ToolCallEnd => self.finish_call(out)?,
Event::Returned | Event::Called => {}
}
}
Ok(())
}
fn finish_call(&mut self, out: &mut String) -> Result<(), String> {
if let Some(call) = self.call.take() {
out.push_str(&tool_markup(&call.name, &call.arguments)?);
}
Ok(())
}
}
/// A parameter name is passed on only when it is a nonempty run of ASCII letters, digits, `_` and `-`.
fn passable_parameter_name(parameter: &str) -> bool {
!parameter.is_empty()
&& parameter
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
}
/// One `<parameter=NAME>` block; a string value is written as it is, any other value as JSON.
fn push_parameter(markup: &mut String, parameter: &str, value: &Value) {
markup.push_str("<parameter=");
markup.push_str(parameter);
markup.push_str(">\n");
match value.as_str() {
Some(text) => markup.push_str(text),
None => markup.push_str(&value.to_string()),
}
markup.push_str("\n</parameter>\n");
}
/// The `<tool_call>` block for a function call with JSON arguments.
fn tool_markup(name: &str, arguments: &str) -> Result<String, String> {
let text = if arguments.trim().is_empty() {
"{}"
} else {
arguments
};
let value: Value = serde_json::from_str(text)
.map_err(|_| format!("the arguments of the call to {name} are not valid JSON"))?;
let object = value
.as_object()
.ok_or_else(|| format!("the arguments of the call to {name} are not a JSON object"))?;
let mut markup = format!("<tool_call>\n<function={name}>\n");
for (parameter, value) in object {
if !passable_parameter_name(parameter) {
return Err(format!(
"the call to {name} has an argument name that cannot be passed on"
));
}
push_parameter(&mut markup, parameter, value);
}
markup.push_str("</function>\n</tool_call>");
Ok(markup)
}
impl TokenDecoder for HarmonyDecoder {
fn push(&mut self, id: u32) -> Result<Vec<u8>, String> {
let mut out = String::new();
if self.bpe.is_special(id) {
let marker = Special::from_token_text(self.bpe.token_text(id).unwrap_or(""));
// a special token cuts any incomplete character
let pending = self.utf8.finish();
if !pending.is_empty() {
let events = self.parser.push(Piece::Text(&pending));
self.translate(events, &mut out)?;
}
if marker == Special::End {
self.message_break = true;
if !self.answered {
self.reasoning_closed = true;
}
}
let events = self.parser.push(Piece::Special(marker));
self.translate(events, &mut out)?;
} else {
let bytes = self.bpe.decode_bytes(&[id]);
let text = self.utf8.push(&bytes);
if !text.is_empty() {
let events = self.parser.push(Piece::Text(&text));
self.translate(events, &mut out)?;
}
}
Ok(out.into_bytes())
}
/// The generation ended: close the open tool call (its closing marker is a terminal token the caller
/// never passes in) and, if the model only reasoned, the reasoning block.
fn finish(&mut self) -> Vec<u8> {
let mut out = String::new();
let pending = self.utf8.finish();
if !pending.is_empty() {
let events = self.parser.push(Piece::Text(&pending));
let _ = self.translate(events, &mut out);
}
let events = self.parser.finish();
let _ = self.translate(events, &mut out);
if self.call.is_some() {
// a call cut off before its end is dropped by an invalid-JSON error here
let _ = self.finish_call(&mut out);
}
if self.thinking && self.reasoning_closed && !self.answered {
out.push_str("</think>\n\n");
self.thinking = false;
}
out.into_bytes()
}
}
#[cfg(test)]
mod tests;
+36 -18
View File
@@ -2,6 +2,7 @@
use super::*;
use crate::wire::Done;
use leleka_gateway_domain::output::{LivePlan, OutputDecoder, OutputEvent, ReadPlan};
/// What the stream is doing between the worker's events: the client connection, the numbering and the text so far.
struct TextRun {
@@ -16,7 +17,6 @@ struct TextRun {
created_at: u64,
pending_response: Value,
output: String,
pending_bytes: Vec<u8>,
}
pub(in crate::responses) fn stream_live_text(
@@ -73,7 +73,6 @@ impl TextRun {
id,
created_at,
output: String::new(),
pending_bytes: Vec::new(),
};
(run, receiver, initial.events)
}
@@ -83,12 +82,17 @@ impl TextRun {
return;
};
self.sequence = sent;
let Some(collected) = self.collect().await else {
let mut decoder = self.tokenizer.output_decoder(ReadPlan::Live(LivePlan {
tools: None,
recovery: false,
keep_raw: false,
}));
let Some(collected) = self.collect(&mut decoder).await else {
return;
};
let mut failure = collected.failure;
if let Some(done) = collected.done.filter(|done| done.finish != Finish::Cancel) {
match self.complete(&done).await {
match self.complete(&mut decoder, &done).await {
Flow::Finished => return,
Flow::Failed(message) => failure = Some(message),
}
@@ -97,9 +101,8 @@ impl TextRun {
}
/// Read the worker's events until DONE or a failure, streaming the text deltas. `None`: the client is gone.
async fn collect(&mut self) -> Option<Collected> {
async fn collect(&mut self, decoder: &mut OutputDecoder<'_>) -> Option<Collected> {
let terminal = self.tokenizer.terminal_ids();
let mut decoder = self.tokenizer.decoder();
let mut text_ended = false;
while let Some(result) = tokio::select! {
biased;
@@ -108,7 +111,7 @@ impl TextRun {
} {
match classify(result, text_ended) {
Next::Token(token) if terminal.contains(&token) => text_ended = true,
Next::Token(token) => match self.push_token(decoder.as_mut(), token).await {
Next::Token(token) => match self.push_token(decoder, token).await {
Ok(true) => {}
Ok(false) => return None,
Err(error) => return Some(Collected::failed(error)),
@@ -121,18 +124,29 @@ impl TextRun {
}
/// Decode one token and stream the text it completes; `Ok(false)`: the client is gone.
async fn push_token(&mut self, decoder: DecoderRef<'_>, token: u32) -> Result<bool, String> {
let bytes = decoder.push(token)?;
self.pending_bytes.extend_from_slice(&bytes);
Ok(self.send_delta(false).await)
async fn push_token(
&mut self,
decoder: &mut OutputDecoder<'_>,
token: u32,
) -> Result<bool, String> {
let events = decoder.push(token).map_err(|error| error.to_string())?;
Ok(self.send_events(events).await)
}
/// Stream the complete UTF-8 text gathered so far (all of it at the end); `false`: the client is gone.
async fn send_delta(&mut self, finish: bool) -> bool {
let delta = drain_utf8(&mut self.pending_bytes, finish);
if delta.is_empty() {
return true;
/// Stream the text of the events; `false`: the client is gone.
async fn send_events(&mut self, events: Vec<OutputEvent>) -> bool {
for event in events {
if let OutputEvent::Text(delta) = event
&& !self.send_delta(delta).await
{
return false;
}
}
true
}
/// Stream one piece of text; `false`: the client is gone.
async fn send_delta(&mut self, delta: String) -> bool {
self.output.push_str(&delta);
let fields = json!({
"response_id": self.id, "item_id": self.item_id, "output_index": 0,
@@ -148,8 +162,12 @@ impl TextRun {
}
/// The worker is done: flush the text, assemble and store the response and send the closing events.
async fn complete(&mut self, done: &Done) -> Flow {
if !self.send_delta(true).await {
async fn complete(&mut self, decoder: &mut OutputDecoder<'_>, done: &Done) -> Flow {
let events = match decoder.finish(done.finish) {
Ok(events) => events,
Err(error) => return Flow::Failed(error.to_string()),
};
if !self.send_events(events).await {
return Flow::Finished;
}
let trace = match self.final_trace(done) {
+7
View File
@@ -6,6 +6,7 @@
//! events work unchanged. For gpt-oss the decoder translates Harmony channels and tool calls
//! (see `harmony_family`).
use crate::output::{OutputDecoder, ReadPlan};
use std::sync::Arc;
/// Which prompt format and output grammar a served model uses.
@@ -32,6 +33,8 @@ pub trait TextCodec: Send + Sync {
fn encode(&self, text: &str, parse_special: bool) -> Result<Vec<u32>, String>;
/// A fresh decoder for one generation.
fn decoder(&self) -> Box<dyn TokenDecoder>;
/// The decoder of one generation that turns the generated ids into output events (see `crate::output`).
fn output_decoder<'a>(&self, plan: ReadPlan<'a>) -> OutputDecoder<'a>;
/// Tokens that end the visible output of a generation (they are not part of the text).
fn terminal_ids(&self) -> Vec<u32>;
/// Token ids of a rendered prompt, the one tokenization used for generation and for counting. The template's own
@@ -114,6 +117,10 @@ impl TextCodec for QwenCodec {
Box::new(QwenDecoder(self.0.clone()))
}
fn output_decoder<'a>(&self, plan: ReadPlan<'a>) -> OutputDecoder<'a> {
OutputDecoder::qwen(self.0.clone(), plan)
}
/// Control-token text inside the messages is marked by the renderer and encoded as ordinary text
/// ([`leleka_tokenizer::Tokenizer::encode_marked`]).
fn encode_prompt(&self, prompt: &str) -> Result<Vec<u32>, String> {
+2
View File
@@ -6,6 +6,7 @@
//! * `chat_completions`: a Chat Completions request as a Responses request, and the chat reply fields.
//! * `responses`: the Responses request and its validation, the rendered prompt, output items, the response trace.
//! * `messages`: the Anthropic Messages request as a Responses request, and the Messages reply fields.
//! * `output`: the canonical `OutputEvent` of a model and the per-family decoders that produce it (S23).
//! * `json_order`: tool results and schemas in the order the client wrote them, or sorted where wanted.
//!
//! Nothing here starts a thread, opens a socket or reads the environment, so the gateway rules can be tested without
@@ -15,6 +16,7 @@ pub mod chat_completions;
pub mod codec;
pub mod json_order;
pub mod messages;
pub mod output;
pub mod reasoning_budget;
pub mod responses;
pub mod sampling;
+31
View File
@@ -0,0 +1,31 @@
//! The canonical output of a model, as the Responses and Messages code reads it (STRA-338 S23).
//!
//! A model family turns the token ids it generates into [`OutputEvent`]s: reasoning, answer text and whole tool
//! calls. Everything after that (the stream loops, the response items, the history) consumes the events only and
//! never asks which family produced them. A family is an adapter behind [`OutputDecoder`]; the dispatch is an enum,
//! so nothing is a trait object per token.
//!
//! Two readings exist because the gateway publishes in two ways:
//!
//! * [`LivePlan`]: text and tool calls are published as they complete (no reasoning, no structured output). Every
//! event of `push` and `finish` is final.
//! * [`AtEndPlan`]: the answer is read once the generation ended (reasoning or structured output). `push` returns
//! only [`OutputEvent::ReasoningDelta`] pieces to show; `finish` returns the events that make up the response.
mod at_end;
mod decoder;
mod event;
mod fold;
mod harmony;
mod live;
mod reasoning_split;
mod utf8;
pub use decoder::{AtEndPlan, LivePlan, OutputDecoder, ReadPlan};
pub use event::{OutputError, OutputEvent};
pub use fold::output_items;
pub use harmony::HarmonyDecoder;
pub use utf8::drain_utf8;
#[cfg(test)]
mod tests;
+221
View File
@@ -0,0 +1,221 @@
//! The reading at the end: the answer is read once the generation is over (reasoning, structured output).
use super::event::{OutputError, OutputEvent};
use super::reasoning_split::ReasoningSplit;
use leleka_gateway_text::tool_output::{self, Notes, Options};
use leleka_worker_protocol::Finish;
use serde_json::Value;
const THINK_END: &[u8] = b"</think>";
/// What a reading at the end needs.
pub struct AtEndPlan {
/// The output starts inside a reasoning block that ends with `</think>`.
pub reasoning: bool,
/// The declarations of the request's tools; `None`: the request declares none and every call stays text.
pub tools: Option<Vec<Value>>,
/// The experimental recovery of drifted tool-call forms.
pub recovery: bool,
/// Keep the split text for the debug copy of a failed output.
pub keep_raw: bool,
}
/// The generation cut into its reasoning and its answer.
struct Split {
reasoning: Option<(String, bool)>,
answer: String,
tokens: u64,
}
pub(super) struct AtEndReader {
plan: AtEndPlan,
bytes: Vec<u8>,
/// With reasoning: the bytes the generation had produced after each token.
ends: Vec<usize>,
tokens: u64,
preview: ReasoningSplit,
notes: Notes,
call_in_reasoning: bool,
copy: Option<(Option<String>, String)>,
}
fn lossy(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
impl AtEndReader {
pub(super) fn new(plan: AtEndPlan) -> Self {
Self {
plan,
bytes: Vec::new(),
ends: Vec::new(),
tokens: 0,
preview: ReasoningSplit::default(),
notes: Notes::default(),
call_in_reasoning: false,
copy: None,
}
}
/// Keep the bytes of one more token; the reasoning text they complete is shown at once.
pub(super) fn push(&mut self, bytes: &[u8]) -> Vec<OutputEvent> {
self.tokens += 1;
self.bytes.extend_from_slice(bytes);
if !self.plan.reasoning {
return Vec::new();
}
self.ends.push(self.bytes.len());
delta_events(self.preview.push(bytes))
}
/// The generation ended; `tail` is what the decoder still held back. The events that make up the response.
pub(super) fn finish(
&mut self,
tail: &[u8],
finish: Finish,
) -> Result<Vec<OutputEvent>, OutputError> {
let mut events = Vec::new();
if self.plan.reasoning && finish == Finish::Length {
events.extend(delta_events(self.preview.finish()));
}
self.bytes.extend_from_slice(tail);
let split = self.split(finish)?;
if self.plan.keep_raw {
let reasoning = split.reasoning.as_ref().map(|(text, _)| text.clone());
self.copy = Some((reasoning, split.answer.clone()));
}
let incomplete = matches!(split.reasoning, Some((_, false)));
if let Some((text, complete)) = split.reasoning {
let tokens = split.tokens;
events.push(OutputEvent::Reasoned {
text,
complete,
tokens,
});
}
if !incomplete {
events.extend(self.read_answer(&split.answer, finish)?);
}
Ok(events)
}
fn split(&mut self, finish: Finish) -> Result<Split, OutputError> {
if !self.plan.reasoning {
return Ok(Split {
reasoning: None,
answer: lossy(&self.bytes),
tokens: 0,
});
}
let boundary = self
.bytes
.windows(THINK_END.len())
.position(|part| part == THINK_END);
match boundary {
Some(at) => Ok(self.split_closed(at)),
None => self.split_unclosed(finish),
}
}
/// The text has a `</think>` at byte `at`: the reasoning before it, the answer after it.
fn split_closed(&self, at: usize) -> Split {
let end = at + THINK_END.len();
Split {
reasoning: Some((lossy(&self.bytes[..at]), true)),
answer: lossy(&self.bytes[end..])
.trim_start_matches('\n')
.to_owned(),
tokens: self.tokens_through(end),
}
}
/// The tokens up to the one that brought the text to `end` bytes (all of them if none did).
fn tokens_through(&self, end: usize) -> u64 {
let first = self.ends.partition_point(|reached| *reached < end);
(first + 1).min(self.ends.len()) as u64
}
/// The tokens whose text lies before byte `at`.
fn tokens_before(&self, at: usize) -> u64 {
if at == 0 {
return 0;
}
self.tokens_through(at)
}
/// The text has no `</think>`.
fn split_unclosed(&mut self, finish: Finish) -> Result<Split, OutputError> {
if finish == Finish::Length {
return Ok(Split {
reasoning: Some((lossy(&self.bytes), false)),
answer: String::new(),
tokens: self.tokens,
});
}
// The model stopped by itself without closing its reasoning. If the text ends on whole tool calls of declared
// tools, the reasoning is what comes before them and they are the answer; otherwise the turn is malformed.
// (The calls were already shown as reasoning text; the reasoning item ends before them.)
let text = lossy(&self.bytes);
let options = self.options(Finish::Stop);
let tools = self.plan.tools.as_deref().unwrap_or(&[]);
let Some(at) = tool_output::calls_at_end(&text, tools, options) else {
return Err(OutputError::Decode(
"reasoning ended without </think>".into(),
));
};
self.call_in_reasoning = true;
Ok(Split {
reasoning: Some((text[..at].to_owned(), true)),
answer: text[at..].to_owned(),
tokens: self.tokens_before(at),
})
}
fn options(&self, finish: Finish) -> Options {
Options {
natural_stop: finish != Finish::Length,
recovery: self.plan.recovery,
}
}
/// The answer as text and whole calls; a call that is not acceptable is a parse error.
fn read_answer(
&mut self,
answer: &str,
finish: Finish,
) -> Result<Vec<OutputEvent>, OutputError> {
let Some(tools) = self.plan.tools.as_deref() else {
return Ok(vec![OutputEvent::Text(answer.to_owned())]);
};
let parsed = tool_output::parse_with(answer, tools, self.options(finish))
.map_err(OutputError::Parse)?;
self.notes = parsed.notes;
let mut events: Vec<OutputEvent> =
parsed.segments.into_iter().map(OutputEvent::from).collect();
if events.is_empty() {
events.push(OutputEvent::Text(String::new()));
}
Ok(events)
}
pub(super) fn notes(&self) -> &Notes {
&self.notes
}
pub(super) fn call_in_reasoning(&self) -> bool {
self.call_in_reasoning
}
pub(super) fn copy(&self) -> Option<(Option<&str>, &str)> {
let (reasoning, answer) = self.copy.as_ref()?;
Some((reasoning.as_deref(), answer))
}
}
fn delta_events(text: String) -> Vec<OutputEvent> {
if text.is_empty() {
Vec::new()
} else {
vec![OutputEvent::ReasoningDelta(text)]
}
}
+144
View File
@@ -0,0 +1,144 @@
//! The decoder a family hands out for one generation: token ids in, [`OutputEvent`]s out.
use super::at_end::AtEndReader;
use super::event::{OutputError, OutputEvent};
use super::harmony::HarmonyDecoder;
use super::live::LiveReader;
use crate::codec::TokenDecoder;
use leleka_gateway_text::tool_output::Notes;
use leleka_worker_protocol::Finish;
use std::sync::Arc;
pub use super::at_end::AtEndPlan;
pub use super::live::LivePlan;
/// How the events of a generation are read.
pub enum ReadPlan<'a> {
Live(LivePlan<'a>),
AtEnd(AtEndPlan),
}
/// The bytes a family's tokens stand for.
enum Bytes {
/// Qwen3.5: the tokenizer decodes one id at a time, with no state.
Qwen(Arc<leleka_tokenizer::Tokenizer>),
/// gpt-oss: the Harmony decoder keeps state and writes the Qwen-style markup.
Harmony(HarmonyDecoder),
/// A fixed byte per id, for the tests of the readers.
#[cfg(test)]
Script(Vec<u8>),
}
impl Bytes {
fn push(&mut self, id: u32) -> Result<Vec<u8>, OutputError> {
match self {
Self::Qwen(tokenizer) => tokenizer
.decode_bytes(&[id])
.map_err(|error| OutputError::Decode(error.to_string())),
Self::Harmony(decoder) => decoder.push(id).map_err(OutputError::Decode),
#[cfg(test)]
Self::Script(bytes) => bytes
.get(id as usize)
.map(|byte| vec![*byte])
.ok_or_else(|| OutputError::Decode(format!("no token {id}"))),
}
}
fn finish(&mut self) -> Vec<u8> {
match self {
Self::Qwen(_) => Vec::new(),
Self::Harmony(decoder) => decoder.finish(),
#[cfg(test)]
Self::Script(_) => Vec::new(),
}
}
}
enum Reader<'a> {
Live(LiveReader<'a>),
AtEnd(AtEndReader),
}
/// The decoder of one generation.
pub struct OutputDecoder<'a> {
bytes: Bytes,
reader: Reader<'a>,
}
impl<'a> OutputDecoder<'a> {
/// The decoder of a Qwen3.5 generation.
pub fn qwen(tokenizer: Arc<leleka_tokenizer::Tokenizer>, plan: ReadPlan<'a>) -> Self {
Self::with_bytes(Bytes::Qwen(tokenizer), plan)
}
/// The decoder of a gpt-oss generation.
pub fn harmony(decoder: HarmonyDecoder, plan: ReadPlan<'a>) -> Self {
Self::with_bytes(Bytes::Harmony(decoder), plan)
}
/// A decoder whose id `n` is byte `n` of `script`.
#[cfg(test)]
pub(super) fn scripted(script: &str, plan: ReadPlan<'a>) -> Self {
Self::with_bytes(Bytes::Script(script.as_bytes().to_vec()), plan)
}
fn with_bytes(bytes: Bytes, plan: ReadPlan<'a>) -> Self {
let reader = match plan {
ReadPlan::Live(plan) => Reader::Live(LiveReader::new(plan)),
ReadPlan::AtEnd(plan) => Reader::AtEnd(AtEndReader::new(plan)),
};
Self { bytes, reader }
}
/// The events one more generated token completes.
pub fn push(&mut self, id: u32) -> Result<Vec<OutputEvent>, OutputError> {
let bytes = self.bytes.push(id)?;
match &mut self.reader {
Reader::Live(reader) => reader.push(&bytes),
Reader::AtEnd(reader) => Ok(reader.push(&bytes)),
}
}
/// The generation ended with `finish`: the events that are left.
pub fn finish(&mut self, finish: Finish) -> Result<Vec<OutputEvent>, OutputError> {
match &mut self.reader {
Reader::Live(reader) => reader.finish(finish),
Reader::AtEnd(reader) => {
let tail = self.bytes.finish();
reader.finish(&tail, finish)
}
}
}
/// What was accepted although the template form of a tool call was not followed.
pub fn notes(&self) -> &Notes {
match &self.reader {
Reader::Live(reader) => reader.notes(),
Reader::AtEnd(reader) => reader.notes(),
}
}
/// The text of a live reading so far, when the plan kept it.
pub fn raw_text(&self) -> Option<&str> {
match &self.reader {
Reader::Live(reader) => reader.raw(),
Reader::AtEnd(_) => None,
}
}
/// Calls were accepted although the reasoning never closed (the reading at the end only).
pub fn accepted_call_in_reasoning(&self) -> bool {
match &self.reader {
Reader::Live(_) => false,
Reader::AtEnd(reader) => reader.call_in_reasoning(),
}
}
/// The reasoning and the answer text as split at the end, when the plan kept them.
pub fn split_text(&self) -> Option<(Option<&str>, &str)> {
match &self.reader {
Reader::Live(_) => None,
Reader::AtEnd(reader) => reader.copy(),
}
}
}
+53
View File
@@ -0,0 +1,53 @@
//! The events a family decoder produces and the errors it reports.
use leleka_gateway_text::tool_output::Segment;
use serde_json::Value;
/// One piece of what the model produced, in the order it produced it.
#[derive(Clone, Debug, PartialEq)]
pub enum OutputEvent {
/// A piece of reasoning text to show while the generation runs. It is not part of the response items.
ReasoningDelta(String),
/// The reasoning of the response: its whole text, whether the model closed it, and the tokens it took.
Reasoned {
text: String,
complete: bool,
tokens: u64,
},
/// Answer text.
Text(String),
/// One whole tool call of a declared tool.
Call { name: String, arguments: Value },
}
impl From<Segment> for OutputEvent {
fn from(segment: Segment) -> Self {
match segment {
Segment::Text(text) => Self::Text(text),
Segment::Call { name, arguments } => Self::Call { name, arguments },
}
}
}
/// Why the output could not be read. The class decides the error the client gets.
#[derive(Clone, Debug, PartialEq)]
pub enum OutputError {
/// The ids could not be turned into the family's text, or the reasoning did not end.
Decode(String),
/// The text was read but a tool call in it is not acceptable.
Parse(String),
}
impl OutputError {
pub fn message(&self) -> &str {
match self {
Self::Decode(message) | Self::Parse(message) => message,
}
}
}
impl std::fmt::Display for OutputError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.message())
}
}
+39
View File
@@ -0,0 +1,39 @@
//! The events of a finished generation as the items of a response.
use super::event::OutputEvent;
use crate::responses::output::OutputItem;
/// The output items of the events and the tokens the reasoning took. A call gets the id `call_<response>_<index>`,
/// where `index` counts the answer events (text and calls) of the response.
pub fn output_items(events: Vec<OutputEvent>, response_id: &str) -> (Vec<OutputItem>, u64) {
let mut items = Vec::new();
let mut reasoning_tokens = 0;
for event in events {
if let OutputEvent::Reasoned { tokens, .. } = &event {
reasoning_tokens = *tokens;
}
let answers = items
.iter()
.filter(|item| !matches!(item, OutputItem::Reasoning { .. }))
.count();
items.extend(item_of(event, response_id, answers));
}
(items, reasoning_tokens)
}
/// The item an event adds to the response; `index` is the number of answer items before it.
fn item_of(event: OutputEvent, response_id: &str, index: usize) -> Option<OutputItem> {
match event {
OutputEvent::ReasoningDelta(_) => None,
OutputEvent::Reasoned { text, complete, .. } => Some(OutputItem::Reasoning {
deltas: vec![text],
complete,
}),
OutputEvent::Text(text) => Some(OutputItem::Text { deltas: vec![text] }),
OutputEvent::Call { name, arguments } => Some(OutputItem::FunctionCall {
name,
call_id: format!("call_{}_{}", &response_id[5..], index),
argument_deltas: vec![arguments.to_string()],
}),
}
}
+209
View File
@@ -0,0 +1,209 @@
//! The gpt-oss adapter: Harmony channels read as the Qwen-style markup the answer reader understands.
//!
//! The generation is a sequence of Harmony messages (analysis, commentary, final). The decoder translates it
//! into the Qwen-style text the reader parses: the reasoning text first (the output is taken to start inside a
//! `<think>` block, as for Qwen), then `</think>`, then the answer text and one `<tool_call>` block per function
//! call. That keeps the validation of tool names and arguments, the history and the streaming events in one place.
use crate::codec::TokenDecoder;
use leleka_harmony::{Event, HarmonyParser, Piece, Special};
use leleka_tokenizer::gguf_bpe::{GgufBpe, Utf8Stream};
use serde_json::Value;
use std::sync::Arc;
/// The tool call being collected: its name and the argument text received so far.
struct OpenCall {
name: String,
arguments: String,
}
/// Translates the generated Harmony token stream to Qwen-style markup, token by token.
pub struct HarmonyDecoder {
bpe: Arc<GgufBpe>,
parser: HarmonyParser,
utf8: Utf8Stream,
/// Output so far is still inside the (virtual) `<think>` block.
thinking: bool,
/// Some answer text or tool call has been written.
answered: bool,
/// An analysis message ended without any answer after it.
reasoning_closed: bool,
/// The previous message ended: separate the next answer text from the last one.
message_break: bool,
call: Option<OpenCall>,
}
impl HarmonyDecoder {
pub fn new(bpe: Arc<GgufBpe>) -> Self {
Self {
bpe,
parser: HarmonyParser::new(),
utf8: Utf8Stream::default(),
thinking: true,
answered: false,
reasoning_closed: false,
message_break: false,
call: None,
}
}
fn close_thinking(&mut self, out: &mut String) {
if self.thinking {
out.push_str("</think>\n\n");
self.thinking = false;
}
}
/// Answer text: after a message break the next answer is separated by a blank line.
fn content(&mut self, text: &str, out: &mut String) {
self.close_thinking(out);
if self.answered && self.message_break {
out.push_str("\n\n");
}
self.answered = true;
self.message_break = false;
out.push_str(text);
}
/// A tool call opens: separated from earlier answer text by a blank line.
fn start_call(&mut self, name: String, out: &mut String) {
self.close_thinking(out);
if self.answered {
out.push_str("\n\n");
}
self.answered = true;
self.message_break = false;
self.call = Some(OpenCall {
name,
arguments: String::new(),
});
}
fn translate(&mut self, events: Vec<Event>, out: &mut String) -> Result<(), String> {
for event in events {
match event {
Event::Reasoning(text) => {
// reasoning after the answer started has nowhere to go; it is hidden anyway
if self.thinking {
out.push_str(&text);
}
}
Event::Content(text) => self.content(&text, out),
Event::ToolCallStart { name, .. } => self.start_call(name, out),
Event::ToolCallArguments(text) => {
if let Some(call) = &mut self.call {
call.arguments.push_str(&text);
}
}
Event::ToolCallEnd => self.finish_call(out)?,
Event::Returned | Event::Called => {}
}
}
Ok(())
}
fn finish_call(&mut self, out: &mut String) -> Result<(), String> {
if let Some(call) = self.call.take() {
out.push_str(&tool_markup(&call.name, &call.arguments)?);
}
Ok(())
}
}
/// A parameter name is passed on only when it is a nonempty run of ASCII letters, digits, `_` and `-`.
fn passable_parameter_name(parameter: &str) -> bool {
!parameter.is_empty()
&& parameter
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
}
/// One `<parameter=NAME>` block; a string value is written as it is, any other value as JSON.
fn push_parameter(markup: &mut String, parameter: &str, value: &Value) {
markup.push_str("<parameter=");
markup.push_str(parameter);
markup.push_str(">\n");
match value.as_str() {
Some(text) => markup.push_str(text),
None => markup.push_str(&value.to_string()),
}
markup.push_str("\n</parameter>\n");
}
/// The `<tool_call>` block for a function call with JSON arguments.
fn tool_markup(name: &str, arguments: &str) -> Result<String, String> {
let text = if arguments.trim().is_empty() {
"{}"
} else {
arguments
};
let value: Value = serde_json::from_str(text)
.map_err(|_| format!("the arguments of the call to {name} are not valid JSON"))?;
let object = value
.as_object()
.ok_or_else(|| format!("the arguments of the call to {name} are not a JSON object"))?;
let mut markup = format!("<tool_call>\n<function={name}>\n");
for (parameter, value) in object {
if !passable_parameter_name(parameter) {
return Err(format!(
"the call to {name} has an argument name that cannot be passed on"
));
}
push_parameter(&mut markup, parameter, value);
}
markup.push_str("</function>\n</tool_call>");
Ok(markup)
}
impl TokenDecoder for HarmonyDecoder {
fn push(&mut self, id: u32) -> Result<Vec<u8>, String> {
let mut out = String::new();
if self.bpe.is_special(id) {
let marker = Special::from_token_text(self.bpe.token_text(id).unwrap_or(""));
// a special token cuts any incomplete character
let pending = self.utf8.finish();
if !pending.is_empty() {
let events = self.parser.push(Piece::Text(&pending));
self.translate(events, &mut out)?;
}
if marker == Special::End {
self.message_break = true;
if !self.answered {
self.reasoning_closed = true;
}
}
let events = self.parser.push(Piece::Special(marker));
self.translate(events, &mut out)?;
} else {
let bytes = self.bpe.decode_bytes(&[id]);
let text = self.utf8.push(&bytes);
if !text.is_empty() {
let events = self.parser.push(Piece::Text(&text));
self.translate(events, &mut out)?;
}
}
Ok(out.into_bytes())
}
/// The generation ended: close the open tool call (its closing marker is a terminal token the caller
/// never passes in) and, if the model only reasoned, the reasoning block.
fn finish(&mut self) -> Vec<u8> {
let mut out = String::new();
let pending = self.utf8.finish();
if !pending.is_empty() {
let events = self.parser.push(Piece::Text(&pending));
let _ = self.translate(events, &mut out);
}
let events = self.parser.finish();
let _ = self.translate(events, &mut out);
if self.call.is_some() {
// a call cut off before its end is dropped by an invalid-JSON error here
let _ = self.finish_call(&mut out);
}
if self.thinking && self.reasoning_closed && !self.answered {
out.push_str("</think>\n\n");
self.thinking = false;
}
out.into_bytes()
}
}
+86
View File
@@ -0,0 +1,86 @@
//! The live reading: text and whole tool calls as the bytes arrive.
use super::event::{OutputError, OutputEvent};
use super::utf8::drain_utf8;
use leleka_gateway_text::tool_output::{Incremental, Notes, Options, Segment};
use leleka_worker_protocol::Finish;
use serde_json::Value;
/// What a live reading needs: the declarations of the request's tools (`None`: no tools, everything is text).
pub struct LivePlan<'a> {
pub tools: Option<&'a [Value]>,
/// The experimental recovery of drifted tool-call forms.
pub recovery: bool,
/// Keep the text read so far, for the debug copy of a failed output.
pub keep_raw: bool,
}
pub(super) struct LiveReader<'a> {
pending: Vec<u8>,
parser: Option<Incremental<'a>>,
raw: Option<String>,
no_notes: Notes,
}
fn events(segments: Vec<Segment>) -> Vec<OutputEvent> {
segments.into_iter().map(OutputEvent::from).collect()
}
impl<'a> LiveReader<'a> {
pub(super) fn new(plan: LivePlan<'a>) -> Self {
let options = Options {
natural_stop: false,
recovery: plan.recovery,
};
Self {
pending: Vec::new(),
parser: plan
.tools
.map(|tools| Incremental::with_options(tools, options)),
raw: plan.keep_raw.then(String::new),
no_notes: Notes::default(),
}
}
/// The events the bytes of one more token complete.
pub(super) fn push(&mut self, bytes: &[u8]) -> Result<Vec<OutputEvent>, OutputError> {
self.pending.extend_from_slice(bytes);
let delta = drain_utf8(&mut self.pending, false);
if delta.is_empty() {
return Ok(Vec::new());
}
if let Some(raw) = self.raw.as_mut() {
raw.push_str(&delta);
}
let Some(parser) = self.parser.as_mut() else {
return Ok(vec![OutputEvent::Text(delta)]);
};
parser.feed(&delta).map(events).map_err(OutputError::Parse)
}
/// The generation ended: the text and calls that are left.
pub(super) fn finish(&mut self, finish: Finish) -> Result<Vec<OutputEvent>, OutputError> {
let rest = drain_utf8(&mut self.pending, true);
let Some(parser) = self.parser.as_mut() else {
return Ok(if rest.is_empty() {
Vec::new()
} else {
vec![OutputEvent::Text(rest)]
});
};
let mut segments = parser.feed(&rest).map_err(OutputError::Parse)?;
let closing = parser.finish_after(finish != Finish::Length);
segments.extend(closing.map_err(OutputError::Parse)?);
Ok(events(segments))
}
pub(super) fn notes(&self) -> &Notes {
self.parser
.as_ref()
.map_or(&self.no_notes, Incremental::notes)
}
pub(super) fn raw(&self) -> Option<&str> {
self.raw.as_deref()
}
}
@@ -0,0 +1,50 @@
//! The reasoning text of a stream that ends with `</think>`, cut out of the byte pieces as they arrive.
use super::utf8::drain_utf8;
const MARKER: &[u8] = b"</think>";
/// Splits the reasoning off a byte stream: the text before `</think>`, which may arrive across pieces.
#[derive(Default)]
pub(super) struct ReasoningSplit {
pending: Vec<u8>,
ended: bool,
}
impl ReasoningSplit {
/// The reasoning text that `bytes` complete; nothing once `</think>` was seen.
pub(super) fn push(&mut self, bytes: &[u8]) -> String {
if self.ended {
return String::new();
}
self.pending.extend_from_slice(bytes);
if let Some(at) = self
.pending
.windows(MARKER.len())
.position(|part| part == MARKER)
{
let text = String::from_utf8_lossy(&self.pending[..at]).into_owned();
self.pending.clear();
self.ended = true;
return text;
}
self.drain_complete()
}
/// The complete text so far, keeping back the bytes that may start `</think>`.
fn drain_complete(&mut self) -> String {
let keep = (1..MARKER.len())
.rev()
.find(|n| self.pending.ends_with(&MARKER[..*n]))
.unwrap_or(0);
let tail = self.pending.split_off(self.pending.len() - keep);
let text = drain_utf8(&mut self.pending, false);
self.pending.extend_from_slice(&tail);
text
}
/// What the generation left unsent when it ended.
pub(super) fn finish(&mut self) -> String {
drain_utf8(&mut self.pending, true)
}
}
+161
View File
@@ -0,0 +1,161 @@
//! Unit tests of the output decoder over a decoder that maps each id to fixed bytes.
use super::*;
use leleka_worker_protocol::Finish;
use serde_json::{Value, json};
fn lookup() -> Vec<Value> {
vec![json!({"type": "function", "name": "lookup", "parameters": {
"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]
}})]
}
const CALL: &str = "<tool_call>\n<function=lookup>\n<parameter=city>\nOslo\n</parameter>\n</function>\n</tool_call>";
/// All events of a script read under `plan`: the events of each push, then those of the finish.
fn run(
text: &str,
plan: ReadPlan<'_>,
finish: Finish,
) -> (Vec<OutputEvent>, Result<Vec<OutputEvent>, OutputError>) {
let mut decoder = OutputDecoder::scripted(text, plan);
let mut pushed = Vec::new();
for id in 0..text.len() as u32 {
pushed.extend(decoder.push(id).unwrap());
}
(pushed, decoder.finish(finish))
}
fn at_end(reasoning: bool, tools: Option<Vec<Value>>) -> ReadPlan<'static> {
ReadPlan::AtEnd(AtEndPlan {
reasoning,
tools,
recovery: false,
keep_raw: false,
})
}
fn live(tools: Option<&[Value]>) -> ReadPlan<'_> {
ReadPlan::Live(LivePlan {
tools,
recovery: false,
keep_raw: false,
})
}
fn text(value: &str) -> OutputEvent {
OutputEvent::Text(value.to_owned())
}
#[test]
fn a_live_reading_without_tools_passes_the_text_on() {
let (pushed, finished) = run("Hello", live(None), Finish::Stop);
assert_eq!(pushed, ["H", "e", "l", "l", "o"].map(text));
assert_eq!(finished.unwrap(), vec![]);
}
#[test]
fn a_live_reading_with_tools_publishes_a_call_when_it_is_whole() {
let tools = lookup();
let script = format!("Checking.\n{CALL}");
let (pushed, finished) = run(&script, live(Some(&tools)), Finish::Stop);
let events: Vec<_> = pushed.into_iter().chain(finished.unwrap()).collect();
let call = OutputEvent::Call {
name: "lookup".into(),
arguments: json!({"city": "Oslo"}),
};
assert!(events.contains(&call), "{events:?}");
let words: String = events
.iter()
.filter_map(|event| match event {
OutputEvent::Text(piece) => Some(piece.as_str()),
_ => None,
})
.collect();
assert_eq!(words, "Checking.");
}
#[test]
fn reasoning_is_previewed_and_returned_whole_at_the_end() {
let (pushed, finished) = run("think</think>\n\nanswer", at_end(true, None), Finish::Stop);
assert_eq!(
pushed,
["t", "h", "i", "n", "k"].map(|piece| OutputEvent::ReasoningDelta(piece.into()))
);
let reasoned = OutputEvent::Reasoned {
text: "think".into(),
complete: true,
tokens: 13,
};
assert_eq!(finished.unwrap(), vec![reasoned, text("answer")]);
}
#[test]
fn unclosed_reasoning_is_incomplete_at_the_length_limit_and_an_error_otherwise() {
let (_, finished) = run("still", at_end(true, None), Finish::Length);
let reasoned = OutputEvent::Reasoned {
text: "still".into(),
complete: false,
tokens: 5,
};
assert_eq!(finished.unwrap(), vec![reasoned]);
let (_, finished) = run("still", at_end(true, None), Finish::Stop);
assert_eq!(
finished,
Err(OutputError::Decode(
"reasoning ended without </think>".into()
))
);
}
#[test]
fn calls_that_end_unclosed_reasoning_are_its_answer() {
let script = format!("I will look.\n{CALL}");
let (_, finished) = run(&script, at_end(true, Some(lookup())), Finish::Stop);
let events = finished.unwrap();
assert!(
matches!(&events[0], OutputEvent::Reasoned { text, complete: true, tokens: 13 } if text == "I will look.\n")
);
assert!(matches!(&events[1], OutputEvent::Call { name, .. } if name == "lookup"));
}
#[test]
fn an_answer_without_calls_is_one_text_event_even_when_empty() {
let (_, finished) = run("", at_end(false, None), Finish::Stop);
assert_eq!(finished.unwrap(), vec![text("")]);
let (_, finished) = run("", at_end(false, Some(lookup())), Finish::Stop);
assert_eq!(finished.unwrap(), vec![text("")]);
}
#[test]
fn a_bad_call_is_a_parse_error_and_a_bad_id_a_decode_error() {
let script = "<tool_call><function=nope></function></tool_call>";
let (_, finished) = run(script, at_end(false, Some(lookup())), Finish::Stop);
assert!(matches!(finished, Err(OutputError::Parse(_))));
let mut decoder = OutputDecoder::scripted("", at_end(false, None));
assert_eq!(
decoder.push(0),
Err(OutputError::Decode("no token 0".into()))
);
}
#[test]
fn items_number_calls_by_their_place_in_the_answer() {
let events = vec![
OutputEvent::Reasoned {
text: "r".into(),
complete: true,
tokens: 3,
},
text("a"),
OutputEvent::Call {
name: "f".into(),
arguments: json!({"x": 1}),
},
];
let (items, tokens) = output_items(events, "resp_ab_1");
assert_eq!(tokens, 3);
assert!(
matches!(&items[2], crate::responses::OutputItem::FunctionCall { call_id, .. } if call_id == "call_ab_1_1")
);
}
+33
View File
@@ -0,0 +1,33 @@
//! Complete UTF-8 text out of a byte stream that may end inside a character.
/// The complete UTF-8 text at the front of `pending`, removed from it. An invalid byte run becomes one U+FFFD;
/// a character that is cut at the end stays in `pending` until more bytes arrive, or, when `finish` is set,
/// becomes U+FFFD.
pub fn drain_utf8(pending: &mut Vec<u8>, finish: bool) -> String {
let mut output = String::new();
while !pending.is_empty() {
match std::str::from_utf8(pending) {
Ok(text) => {
output.push_str(text);
pending.clear();
}
Err(error) => {
let valid = error.valid_up_to();
if valid > 0 {
output.push_str(std::str::from_utf8(&pending[..valid]).expect("UTF-8 prefix"));
pending.drain(..valid);
}
if let Some(invalid) = error.error_len() {
output.push('\u{fffd}');
pending.drain(..invalid);
} else if finish {
output.push('\u{fffd}');
pending.clear();
} else {
break;
}
}
}
}
output
}