Merge remote-tracking branch 'origin/claude/hexagonal-s23' into claude/hexagonal-integ
This commit is contained in:
@@ -14,7 +14,7 @@
|
||||
"dyn-trait:leleka-engine-fake": 1,
|
||||
"dyn-trait:leleka-engine-qwen35-cuda": 53,
|
||||
"dyn-trait:leleka-experimental-ref": 3,
|
||||
"dyn-trait:leleka-gateway-domain": 4,
|
||||
"dyn-trait:leleka-gateway-domain": 2,
|
||||
"dyn-trait:leleka-gptoss": 10,
|
||||
"dyn-trait:leleka-gptoss-igpu": 4,
|
||||
"dyn-trait:leleka-gptoss-npu": 4,
|
||||
@@ -22,7 +22,7 @@
|
||||
"dyn-trait:leleka-memory": 17,
|
||||
"dyn-trait:leleka-model-format": 8,
|
||||
"dyn-trait:leleka-tokenizer": 1,
|
||||
"dyn-trait:strata-control": 12,
|
||||
"dyn-trait:strata-control": 11,
|
||||
"dyn-trait:strata-desktop-core": 2,
|
||||
"env-read:leleka-cpu-kernels": 1,
|
||||
"env-read:leleka-cpu-worker": 2,
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use leleka_gateway_domain::output::{HarmonyDecoder, OutputDecoder, ReadPlan};
|
||||
use leleka_gateway_domain::output::{AtEndDecoder, AtEndPlan, HarmonyDecoder};
|
||||
use leleka_harmony::SENTINELS;
|
||||
use leleka_tokenizer::gguf_bpe::GgufBpe;
|
||||
|
||||
use crate::codec::{Family, TextCodec, TokenDecoder};
|
||||
use crate::codec::{Family, TextCodec};
|
||||
use crate::sampler_limit::{Sampler, SamplingLimit};
|
||||
|
||||
/// Tokens that end the visible output of a generation.
|
||||
const TERMINAL_MARKERS: [&str; 3] = ["<|return|>", "<|call|>", "<|endoftext|>"];
|
||||
@@ -88,16 +89,21 @@ impl TextCodec for GptOssCodec {
|
||||
}
|
||||
|
||||
/// The worker's `GEN` line takes temperature, top_p and seed only.
|
||||
fn sampling_limit(&self) -> Option<&'static str> {
|
||||
Some("the gpt-oss family supports temperature, top_p and seed only")
|
||||
fn sampling_limit(&self) -> Option<SamplingLimit> {
|
||||
Some(SamplingLimit {
|
||||
unsupported: &[
|
||||
Sampler::TopK,
|
||||
Sampler::MinP,
|
||||
Sampler::RepetitionPenalty,
|
||||
Sampler::FrequencyPenalty,
|
||||
Sampler::PresencePenalty,
|
||||
],
|
||||
message: "the gpt-oss family supports temperature, top_p and seed only",
|
||||
})
|
||||
}
|
||||
|
||||
fn decoder(&self) -> Box<dyn TokenDecoder> {
|
||||
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 at_end_decoder(&self, plan: AtEndPlan) -> AtEndDecoder {
|
||||
AtEndDecoder::harmony(HarmonyDecoder::new(self.bpe.clone()), plan)
|
||||
}
|
||||
|
||||
fn terminal_ids(&self) -> Vec<u32> {
|
||||
|
||||
@@ -36,8 +36,19 @@ fn script(c: &GptOssCodec, parts: &[&str]) -> Vec<u32> {
|
||||
ids
|
||||
}
|
||||
|
||||
/// The markup the Harmony decoder writes for the ids, or its first error.
|
||||
fn try_decode(c: &GptOssCodec, ids: &[u32]) -> Result<String, String> {
|
||||
let mut decoder = HarmonyDecoder::new(c.bpe.clone());
|
||||
let mut bytes = Vec::new();
|
||||
for id in ids {
|
||||
bytes.extend(decoder.push(*id)?);
|
||||
}
|
||||
bytes.extend(decoder.finish());
|
||||
Ok(String::from_utf8(bytes).unwrap())
|
||||
}
|
||||
|
||||
fn decode(c: &GptOssCodec, ids: &[u32]) -> String {
|
||||
String::from_utf8(crate::codec::decode_all(c, ids).unwrap()).unwrap()
|
||||
try_decode(c, ids).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -182,7 +193,7 @@ fn invalid_tool_arguments_are_an_error_when_the_call_ends() {
|
||||
let c = codec();
|
||||
for tokens in INVALID_TOOL_CALLS {
|
||||
let ids = script(&c, tokens);
|
||||
assert!(crate::codec::decode_all(&c, &ids).is_err());
|
||||
assert!(try_decode(&c, &ids).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,3 +241,21 @@ fn terminal_ids_cover_the_generation_end_markers() {
|
||||
}
|
||||
assert_eq!(c.family(), Family::GptOss);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gptoss_reasons_whatever_the_effort_and_has_no_live_reading() {
|
||||
use leleka_gateway_domain::output::LivePlan;
|
||||
use leleka_gateway_domain::responses::{CreateRequest, reasoning_enabled};
|
||||
let c = codec();
|
||||
let request: CreateRequest = serde_json::from_value(
|
||||
serde_json::json!({"model": "m", "input": "x", "reasoning": {"effort": "none"}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(reasoning_enabled(&request, &c));
|
||||
let plan = LivePlan {
|
||||
tools: None,
|
||||
recovery: false,
|
||||
keep_raw: false,
|
||||
};
|
||||
assert!(c.live_decoder(plan).is_none());
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ macro_rules! wlog {
|
||||
/// The boxed error the command-line and offline-tool functions return.
|
||||
pub type BoxError = Box<dyn std::error::Error>;
|
||||
|
||||
pub use leleka_gateway_domain::{codec, json_order, reasoning_budget, sampling};
|
||||
pub use leleka_gateway_domain::{codec, json_order, reasoning_budget, sampler_limit, sampling};
|
||||
|
||||
pub mod adapters;
|
||||
pub mod app;
|
||||
|
||||
@@ -41,7 +41,6 @@ use crate::{
|
||||
ports::{SharedClock, SharedResponseStore, response_store::InputItemsQuery},
|
||||
response_tools::Catalog,
|
||||
tokenizer::{LiteralMarks, Tokenizer},
|
||||
tool_output,
|
||||
wire::{Event, Finish, Generate},
|
||||
worker::{GenerationCommand, GenerationResult, WorkerState},
|
||||
};
|
||||
@@ -96,9 +95,7 @@ use stream::*;
|
||||
mod tool_recovery;
|
||||
pub use tool_recovery::set_tool_call_recovery;
|
||||
#[allow(unused_imports)]
|
||||
use tool_recovery::{at_end_plan, finish_output, log_tool_notes, tool_call_recovery};
|
||||
#[cfg(test)]
|
||||
use tool_recovery::{parse_output_items, parse_output_items_after};
|
||||
use tool_recovery::{at_end_plan, finish_generation, log_tool_notes, tool_call_recovery};
|
||||
|
||||
// The pure part of the protocol lives in `leleka-gateway-domain`; the old paths stay.
|
||||
pub use leleka_gateway_domain::responses::{
|
||||
@@ -106,11 +103,13 @@ pub use leleka_gateway_domain::responses::{
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
use leleka_gateway_domain::responses::{
|
||||
flat_tools, is_structured, parse_output_items_with, reasoning_effort, reasoning_enabled,
|
||||
reject_remote_refs, render_request_with, text_part, tool_schema_accepted,
|
||||
unsupported_gptoss_sampling, validate_live_subset, validate_text_format,
|
||||
flat_tools, is_structured, reasoning_effort, reasoning_enabled, reject_remote_refs,
|
||||
render_request_with, text_part, tool_schema_accepted, validate_live_subset,
|
||||
validate_text_format,
|
||||
};
|
||||
|
||||
use leleka_gateway_domain::sampler_limit::{drop_unsupported_samplers, unsupported_sampler};
|
||||
|
||||
#[cfg(test)]
|
||||
mod golden;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -63,13 +63,13 @@ pub(super) fn check_live_features(
|
||||
if let Some(limit) = tokenizer.sampling_limit() {
|
||||
// The worker of some families takes few samplers. An explicit request for one it does not have is a client
|
||||
// error; defaults from the config or the shared settings are dropped.
|
||||
if let Some(param) = unsupported_gptoss_sampling(&request.sampling()) {
|
||||
if let Some(param) = unsupported_sampler(&request.sampling(), &limit) {
|
||||
return Err(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
"unsupported_parameter",
|
||||
Some(param),
|
||||
limit,
|
||||
limit.message,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -86,13 +86,8 @@ pub(super) fn apply_sampling_defaults(
|
||||
&state.services.settings.merged(),
|
||||
&state.services.settings.shared(),
|
||||
);
|
||||
if tokenizer.sampling_limit().is_some() {
|
||||
request.top_k = None;
|
||||
request.min_p = None;
|
||||
request.repetition_penalty = None;
|
||||
request.frequency_penalty = None;
|
||||
request.presence_penalty = None;
|
||||
request.penalty_last_n = None;
|
||||
if let Some(limit) = tokenizer.sampling_limit() {
|
||||
drop_unsupported_samplers(request, &limit);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use super::*;
|
||||
use crate::{ports::engine::SharedEngine, wire::Done};
|
||||
use leleka_gateway_domain::output::{OutputError, OutputEvent, ReadPlan, output_items};
|
||||
use leleka_gateway_domain::output::{OutputError, OutputEvent, output_items};
|
||||
|
||||
/// Hand the request to the engine and answer with the server-sent events of its tokens.
|
||||
pub(super) async fn submit_streaming(
|
||||
@@ -141,14 +141,14 @@ async fn read_output(
|
||||
output_ids: Vec<u32>,
|
||||
finish: Finish,
|
||||
) -> Result<Vec<OutputEvent>, Response> {
|
||||
let plan = at_end_plan(request, tokenizer.as_ref());
|
||||
let plan = at_end_plan(request, tokenizer.as_ref(), false);
|
||||
let tokenizer = tokenizer.clone();
|
||||
let read = tokio::task::spawn_blocking(move || {
|
||||
let mut decoder = tokenizer.output_decoder(ReadPlan::AtEnd(plan));
|
||||
let mut decoder = tokenizer.at_end_decoder(plan);
|
||||
for id in &output_ids {
|
||||
decoder.push(*id)?;
|
||||
}
|
||||
finish_output(&mut decoder, finish)
|
||||
finish_generation(&mut decoder, finish)
|
||||
})
|
||||
.await;
|
||||
match read {
|
||||
|
||||
@@ -84,9 +84,14 @@ fn parse_case(case: &Value) -> Value {
|
||||
Ok(request) => request,
|
||||
Err(error) => return error,
|
||||
};
|
||||
let output = case["output"].as_str().unwrap().to_owned();
|
||||
let output = case["output"].as_str().unwrap();
|
||||
let natural_stop = case["natural_stop"].as_bool().unwrap();
|
||||
match parse_output_items_after(&request, output, "resp_golden_1", natural_stop) {
|
||||
let finish = if natural_stop {
|
||||
Finish::Stop
|
||||
} else {
|
||||
Finish::Length
|
||||
};
|
||||
match tests::answer_items(&request, output, "resp_golden_1", finish) {
|
||||
Ok(items) => json!({"items": items.iter().map(item_json).collect::<Vec<_>>()}),
|
||||
Err(error) => json!({"error": error}),
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
/// What a stream fails with when its model has no live reading of its output (it always reasons).
|
||||
pub(super) const NO_LIVE_READING: &str = "the output of this model cannot be read live";
|
||||
|
||||
mod buffered;
|
||||
mod text;
|
||||
mod tool_run;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::*;
|
||||
use crate::wire::Done;
|
||||
use leleka_gateway_domain::output::{OutputDecoder, OutputEvent, ReadPlan, output_items};
|
||||
use leleka_gateway_domain::output::{AtEndDecoder, GENERATION_ENDED, OutputEvent, output_items};
|
||||
|
||||
/// What the stream is doing between the worker's events: the client connection, the numbering and the decoder.
|
||||
struct BufferedRun {
|
||||
@@ -17,7 +17,8 @@ struct BufferedRun {
|
||||
created_at: u64,
|
||||
thinking: bool,
|
||||
pending: Value,
|
||||
decoder: Option<OutputDecoder<'static>>,
|
||||
initial: Vec<Value>,
|
||||
decoder: Option<AtEndDecoder>,
|
||||
}
|
||||
|
||||
pub(in crate::responses) fn stream_live_buffered(
|
||||
@@ -26,8 +27,8 @@ pub(in crate::responses) fn stream_live_buffered(
|
||||
source: mpsc::Receiver<Result<Event, String>>,
|
||||
env: StreamEnv,
|
||||
) -> Response {
|
||||
let (run, initial_events, receiver) = BufferedRun::start(request, tokenizer, source, env);
|
||||
tokio::spawn(run.run(initial_events));
|
||||
let (run, receiver) = BufferedRun::build(request, tokenizer, source, env);
|
||||
tokio::spawn(run.run());
|
||||
sse_response(receiver)
|
||||
}
|
||||
|
||||
@@ -59,15 +60,6 @@ fn initial_trace(
|
||||
.expect("validated structured request has a valid initial envelope")
|
||||
}
|
||||
|
||||
/// Whether the output starts inside a reasoning block, and the decoder that reads the generation at its end.
|
||||
fn reading(request: &CreateRequest, tokenizer: &SharedCodec) -> (bool, OutputDecoder<'static>) {
|
||||
let plan = at_end_plan(request, tokenizer.as_ref());
|
||||
(
|
||||
plan.reasoning,
|
||||
tokenizer.output_decoder(ReadPlan::AtEnd(plan)),
|
||||
)
|
||||
}
|
||||
|
||||
/// The usage of a finished generation; the reasoning tokens counted from the output never exceed what was generated.
|
||||
fn usage_with_reasoning(done: &Done, reasoning_tokens: u64) -> Usage {
|
||||
Usage {
|
||||
@@ -77,22 +69,25 @@ fn usage_with_reasoning(done: &Done, reasoning_tokens: u64) -> Usage {
|
||||
}
|
||||
|
||||
impl BufferedRun {
|
||||
/// The run for a new response, the initial events to send first and the receiver the client reads by.
|
||||
fn start(
|
||||
/// The run for a new response and the receiver the client reads it by.
|
||||
fn build(
|
||||
request: CreateRequest,
|
||||
tokenizer: SharedCodec,
|
||||
source: mpsc::Receiver<Result<Event, String>>,
|
||||
env: StreamEnv,
|
||||
) -> (Self, Vec<Value>, mpsc::Receiver<Value>) {
|
||||
) -> (Self, mpsc::Receiver<Value>) {
|
||||
let now = env.now();
|
||||
let id = response_id(now);
|
||||
let created_at = now.as_secs();
|
||||
let (thinking, decoder) = reading(&request, &tokenizer);
|
||||
let plan = at_end_plan(&request, tokenizer.as_ref(), true);
|
||||
let thinking = plan.reasoning;
|
||||
let initial = initial_trace(&request, &id, created_at, thinking);
|
||||
let (sender, receiver) = mpsc::channel(16);
|
||||
let run = BufferedRun {
|
||||
decoder: Some(tokenizer.at_end_decoder(plan)),
|
||||
reasoning_id: format!("rs_{}_0", &id[5..]),
|
||||
pending: initial.events[0]["response"].clone(),
|
||||
initial: initial.events,
|
||||
request,
|
||||
tokenizer,
|
||||
source,
|
||||
@@ -102,9 +97,8 @@ impl BufferedRun {
|
||||
id,
|
||||
created_at,
|
||||
thinking,
|
||||
decoder: Some(decoder),
|
||||
};
|
||||
(run, initial.events, receiver)
|
||||
(run, receiver)
|
||||
}
|
||||
|
||||
/// The number of events of the initial trace that are sent at once and not again at the end.
|
||||
@@ -112,7 +106,8 @@ impl BufferedRun {
|
||||
if self.thinking { 4 } else { 2 }
|
||||
}
|
||||
|
||||
async fn run(mut self, initial_events: Vec<Value>) {
|
||||
async fn run(mut self) {
|
||||
let initial_events = std::mem::take(&mut self.initial);
|
||||
let Some(sent) = send_prelude(&self.sender, initial_events, self.prelude_len()).await
|
||||
else {
|
||||
return;
|
||||
@@ -156,7 +151,7 @@ impl BufferedRun {
|
||||
|
||||
/// Decode one token and stream the reasoning it completes. `Ok(false)`: the client is gone.
|
||||
async fn push_token(&mut self, token: u32) -> Result<bool, String> {
|
||||
let decoder = self.decoder.as_mut().expect("the decoder is finished once");
|
||||
let decoder = self.decoder.as_mut().ok_or(GENERATION_ENDED)?;
|
||||
let events = decoder.push(token).map_err(|error| error.to_string())?;
|
||||
Ok(self.send_previews(events).await.is_some())
|
||||
}
|
||||
@@ -210,8 +205,8 @@ impl BufferedRun {
|
||||
/// End the generation and read the response out of it, off the async threads.
|
||||
async fn finish_events(&mut self, finish: Finish) -> Result<Vec<OutputEvent>, String> {
|
||||
let post_decode = crate::stage_trace::span("post_decode");
|
||||
let mut decoder = self.decoder.take().expect("the decoder is finished once");
|
||||
let events = tokio::task::spawn_blocking(move || finish_output(&mut decoder, finish))
|
||||
let mut decoder = self.decoder.take().ok_or(GENERATION_ENDED)?;
|
||||
let events = tokio::task::spawn_blocking(move || finish_generation(&mut decoder, finish))
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|result| result.map_err(|error| error.to_string()));
|
||||
@@ -268,3 +263,6 @@ impl BufferedRun {
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
//! The buffered stream when its generation is read twice.
|
||||
|
||||
use super::*;
|
||||
use crate::responses::tests::{make_request, test_tokenizer};
|
||||
use std::fs;
|
||||
|
||||
/// A generation ends once: reading it again fails the response (`response.failed`) and does not panic.
|
||||
#[tokio::test]
|
||||
async fn finishing_the_generation_twice_fails_the_response() {
|
||||
let (codec, root) = test_tokenizer();
|
||||
let request = make_request(json!({"reasoning": {"effort": "low"}}));
|
||||
let (_worker, source) = mpsc::channel(1);
|
||||
let (mut run, mut client) = BufferedRun::build(request, codec, source, StreamEnv::none());
|
||||
assert!(run.finish_events(Finish::Length).await.is_ok());
|
||||
let again = run.finish_events(Finish::Length).await;
|
||||
assert_eq!(again, Err(GENERATION_ENDED.to_owned()));
|
||||
run.fail(again.err()).await;
|
||||
let event = client.recv().await.unwrap();
|
||||
assert_eq!(event["type"], "response.failed");
|
||||
assert_eq!(event["response"]["error"]["message"], GENERATION_ENDED);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
/// A token pushed after the generation ended is a failure of the stream, not a panic.
|
||||
#[tokio::test]
|
||||
async fn a_token_after_the_end_is_a_failure() {
|
||||
let (codec, root) = test_tokenizer();
|
||||
let request = make_request(json!({"reasoning": {"effort": "low"}}));
|
||||
let (_worker, source) = mpsc::channel(1);
|
||||
let (mut run, _client) = BufferedRun::build(request, codec, source, StreamEnv::none());
|
||||
let _ = run.finish_events(Finish::Length).await;
|
||||
assert_eq!(run.push_token(65).await, Err(GENERATION_ENDED.to_owned()));
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::*;
|
||||
use crate::wire::Done;
|
||||
use leleka_gateway_domain::output::{LivePlan, OutputDecoder, OutputEvent, ReadPlan};
|
||||
use leleka_gateway_domain::output::{LiveDecoder, LivePlan, OutputEvent};
|
||||
|
||||
/// What the stream is doing between the worker's events: the client connection, the numbering and the text so far.
|
||||
struct TextRun {
|
||||
@@ -82,11 +82,14 @@ impl TextRun {
|
||||
return;
|
||||
};
|
||||
self.sequence = sent;
|
||||
let mut decoder = self.tokenizer.output_decoder(ReadPlan::Live(LivePlan {
|
||||
let plan = LivePlan {
|
||||
tools: None,
|
||||
recovery: false,
|
||||
keep_raw: false,
|
||||
}));
|
||||
};
|
||||
let Some(mut decoder) = self.tokenizer.live_decoder(plan) else {
|
||||
return self.fail(Some(NO_LIVE_READING.to_owned())).await;
|
||||
};
|
||||
let Some(collected) = self.collect(&mut decoder).await else {
|
||||
return;
|
||||
};
|
||||
@@ -101,7 +104,7 @@ 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, decoder: &mut OutputDecoder<'_>) -> Option<Collected> {
|
||||
async fn collect(&mut self, decoder: &mut LiveDecoder<'_>) -> Option<Collected> {
|
||||
let terminal = self.tokenizer.terminal_ids();
|
||||
let mut text_ended = false;
|
||||
while let Some(result) = tokio::select! {
|
||||
@@ -126,7 +129,7 @@ impl TextRun {
|
||||
/// Decode one token and stream the text it completes; `Ok(false)`: the client is gone.
|
||||
async fn push_token(
|
||||
&mut self,
|
||||
decoder: &mut OutputDecoder<'_>,
|
||||
decoder: &mut LiveDecoder<'_>,
|
||||
token: u32,
|
||||
) -> Result<bool, String> {
|
||||
let events = decoder.push(token).map_err(|error| error.to_string())?;
|
||||
@@ -162,7 +165,7 @@ impl TextRun {
|
||||
}
|
||||
|
||||
/// The worker is done: flush the text, assemble and store the response and send the closing events.
|
||||
async fn complete(&mut self, decoder: &mut OutputDecoder<'_>, done: &Done) -> Flow {
|
||||
async fn complete(&mut self, decoder: &mut LiveDecoder<'_>, done: &Done) -> Flow {
|
||||
let events = match decoder.finish(done.finish) {
|
||||
Ok(events) => events,
|
||||
Err(error) => return Flow::Failed(error.to_string()),
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::tools::ToolStream;
|
||||
use super::*;
|
||||
use crate::wire::Done;
|
||||
use leleka_gateway_domain::output::{LivePlan, OutputDecoder, OutputEvent, ReadPlan};
|
||||
use leleka_gateway_domain::output::{LiveDecoder, LivePlan, OutputEvent};
|
||||
|
||||
/// What the stream is doing between the worker's events: the published items and whether to keep the debug copy.
|
||||
struct ToolsRun {
|
||||
@@ -72,7 +72,9 @@ impl ToolsRun {
|
||||
recovery: tool_call_recovery(),
|
||||
keep_raw: self.keep_raw,
|
||||
};
|
||||
let mut decoder = self.tokenizer.output_decoder(ReadPlan::Live(plan));
|
||||
let Some(mut decoder) = self.tokenizer.live_decoder(plan) else {
|
||||
return self.fail(Some(NO_LIVE_READING.to_owned()), None).await;
|
||||
};
|
||||
let Some(collected) = self.collect(&mut decoder).await else {
|
||||
return;
|
||||
};
|
||||
@@ -88,7 +90,7 @@ impl ToolsRun {
|
||||
|
||||
/// Read the worker's events until DONE or a failure, publishing the text and calls the tokens complete.
|
||||
/// `None`: the client is gone.
|
||||
async fn collect(&mut self, decoder: &mut OutputDecoder<'_>) -> Option<Collected> {
|
||||
async fn collect(&mut self, decoder: &mut LiveDecoder<'_>) -> Option<Collected> {
|
||||
let terminal = self.tokenizer.terminal_ids();
|
||||
let mut text_ended = false;
|
||||
while let Some(result) = tokio::select! {
|
||||
@@ -113,7 +115,7 @@ impl ToolsRun {
|
||||
/// Decode one token and publish the text and calls it makes whole.
|
||||
async fn push_token(
|
||||
&mut self,
|
||||
decoder: &mut OutputDecoder<'_>,
|
||||
decoder: &mut LiveDecoder<'_>,
|
||||
token: u32,
|
||||
) -> Result<(), String> {
|
||||
let events = decoder.push(token).map_err(|error| error.to_string())?;
|
||||
@@ -130,7 +132,7 @@ impl ToolsRun {
|
||||
}
|
||||
|
||||
/// The worker is done: publish what is left, close the items, store the response and send the terminal event.
|
||||
async fn complete(&mut self, decoder: &mut OutputDecoder<'_>, done: &Done) -> Flow {
|
||||
async fn complete(&mut self, decoder: &mut LiveDecoder<'_>, done: &Done) -> Flow {
|
||||
let parsed = decoder.finish(done.finish);
|
||||
log_tool_notes(decoder.notes());
|
||||
let closed = match parsed {
|
||||
|
||||
@@ -8,7 +8,6 @@ mod input_items;
|
||||
mod live;
|
||||
mod live_endpoint;
|
||||
mod live_tools;
|
||||
mod output_golden;
|
||||
mod reasoning;
|
||||
mod reasoning_live;
|
||||
mod sampling;
|
||||
@@ -19,4 +18,4 @@ mod text_preview;
|
||||
mod tool_policy;
|
||||
mod tool_replay;
|
||||
mod validation;
|
||||
pub(super) use fixtures::test_marks;
|
||||
pub(super) use fixtures::{answer_items, make_request, test_marks, test_tokenizer};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Custom and console-envelope tools: identity, input events, grammar failures and the live stream.
|
||||
|
||||
use super::super::*;
|
||||
use super::fixtures::{make_request, test_tokenizer, usage};
|
||||
use super::fixtures::{answer_items, make_request, test_tokenizer, usage};
|
||||
use super::live::{assert_sequence, feed_tokens, finish_stream, read_until_type};
|
||||
use crate::responses::StreamEnv as Env;
|
||||
use crate::wire::Done;
|
||||
@@ -55,7 +55,7 @@ async fn console_envelope_namespaced_calls_preserve_identity_and_replay() {
|
||||
let markup = format!(
|
||||
"<tool_call>\n<function={alias}>\n<parameter=path>\nanswer.txt\n</parameter>\n</function>\n</tool_call>"
|
||||
);
|
||||
let items = parse_output_items(&request, markup.clone(), "resp_console").unwrap();
|
||||
let items = answer_items(&request, &markup, "resp_console", Finish::Length).unwrap();
|
||||
let trace = ResponseTrace::build(&request, &items, usage(), "resp_console", 1, 2).unwrap();
|
||||
let output = trace.response["output"][0].clone();
|
||||
assert_eq!(output["name"], "read");
|
||||
@@ -127,7 +127,7 @@ fn custom_text_tools_preserve_input_events_namespaces_and_replay() {
|
||||
let markup = format!(
|
||||
"<tool_call>\n<function={alias}>\n<parameter=input>\n{input}\n</parameter>\n</function>\n</tool_call>"
|
||||
);
|
||||
let items = parse_output_items(&request, markup.clone(), "resp_custom").unwrap();
|
||||
let items = answer_items(&request, &markup, "resp_custom", Finish::Length).unwrap();
|
||||
let trace = ResponseTrace::build(&request, &items, usage(), "resp_custom", 1, 2).unwrap();
|
||||
let call = trace.response["output"][0].clone();
|
||||
assert_custom_call_item(&call, input);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::super::*;
|
||||
use crate::tokenizer::Tokenizer;
|
||||
use crate::tokenizer_assets::QWEN35_PATTERN;
|
||||
use leleka_gateway_domain::output::{AtEndPlan, output_items};
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -97,3 +98,31 @@ pub(in super::super) fn test_marks() -> LiteralMarks {
|
||||
])
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The items a model answer without reasoning becomes through the Qwen decoder: text, with tool calls as markup;
|
||||
/// `finish` is how the generation ended.
|
||||
pub(in super::super) fn answer_items(
|
||||
request: &CreateRequest,
|
||||
output: &str,
|
||||
id: &str,
|
||||
finish: Finish,
|
||||
) -> Result<Vec<OutputItem>, String> {
|
||||
let (codec, root) = test_tokenizer();
|
||||
let plan = AtEndPlan {
|
||||
reasoning: false,
|
||||
preview: false,
|
||||
tools: (!request.tools.is_empty()).then(|| flat_tools(request)),
|
||||
recovery: false,
|
||||
keep_raw: false,
|
||||
};
|
||||
let mut decoder = codec.at_end_decoder(plan);
|
||||
let pushed = codec
|
||||
.encode(output, false)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.try_for_each(|token| decoder.push(token).map(drop));
|
||||
let read = pushed.and_then(|()| decoder.finish(finish));
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
read.map(|events| output_items(events, id).0)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
//! Golden captures of what the gateway answers for a scripted model output, for both families (STRA-338 S23).
|
||||
//!
|
||||
//! A scripted worker answers the real `create` handler with a fixed token sequence, once as a stream and once as
|
||||
//! a buffered answer. The bytes the client would read (status, content type, SSE frames or the JSON body) are
|
||||
//! stored after the volatile parts (ids made of the clock and a counter, timestamps) are replaced. The scripts
|
||||
//! are in `tests/fixtures/golden/output_cases.json`, the expected captures in `output_events.json`; the S23
|
||||
//! steps move the output decoding behind `OutputEvent` and must not change one byte of the captures. All
|
||||
//! scripts are synthetic: no capture of a real session is committed.
|
||||
|
||||
use super::super::*;
|
||||
use super::live::{done, ready_state};
|
||||
use crate::codec::{QwenCodec, TextCodec};
|
||||
use crate::harmony_family::GptOssCodec;
|
||||
use axum::extract::State;
|
||||
use http_body_util::BodyExt;
|
||||
use leleka_tokenizer::gguf_bpe::GgufBpe;
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
/// The two codecs a case may run under, and the vocabulary of the gpt-oss one for turning a script into ids.
|
||||
struct Codecs {
|
||||
qwen: Arc<QwenCodec>,
|
||||
gptoss: Arc<GptOssCodec>,
|
||||
gptoss_vocabulary: GgufBpe,
|
||||
}
|
||||
|
||||
/// The vocabulary of the gpt-oss test codec: the byte tokens and the Harmony markers as control tokens.
|
||||
fn gptoss_vocabulary() -> GgufBpe {
|
||||
let chars = leleka_tokenizer::gguf_bpe::byte_alphabet();
|
||||
let mut tokens: Vec<String> = chars.iter().map(|c| c.to_string()).collect();
|
||||
let mut types = vec![1i64; 256];
|
||||
let markers = [
|
||||
"<|start|>",
|
||||
"<|end|>",
|
||||
"<|message|>",
|
||||
"<|channel|>",
|
||||
"<|call|>",
|
||||
];
|
||||
for marker in markers
|
||||
.into_iter()
|
||||
.chain(["<|return|>", "<|constrain|>", "<|endoftext|>"])
|
||||
{
|
||||
tokens.push(marker.to_owned());
|
||||
types.push(3);
|
||||
}
|
||||
let parts: Vec<&str> = tokens.iter().map(String::as_str).collect();
|
||||
GgufBpe::from_parts(&parts, &types, &[], None, None, None).unwrap()
|
||||
}
|
||||
|
||||
/// The token ids of a script: `@name` is the special token `name`, anything else is text as byte-level tokens.
|
||||
fn script_ids(case: &Value, codecs: &Codecs) -> Vec<u32> {
|
||||
let gptoss = case["family"] == "gptoss";
|
||||
let mut ids = Vec::new();
|
||||
for part in case["script"].as_array().unwrap() {
|
||||
let part = part.as_str().unwrap();
|
||||
match (gptoss, part.strip_prefix('@')) {
|
||||
(true, Some(name)) => ids.push(codecs.gptoss_vocabulary.token_id(name).unwrap()),
|
||||
(true, None) => ids.extend(codecs.gptoss_vocabulary.encode(part, false)),
|
||||
(false, Some(name)) => ids.push(codecs.qwen.special_id(name).unwrap()),
|
||||
(false, None) => ids.extend(codecs.qwen.encode(part, false).unwrap()),
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The events a worker sends for the script and its end: `stop`, `length` or `fail:<message>`.
|
||||
fn worker_events(ids: &[u32], end: &str) -> Vec<Result<Event, String>> {
|
||||
let mut events: Vec<Result<Event, String>> =
|
||||
ids.iter().map(|id| Ok(Event::Token(*id))).collect();
|
||||
let finish = match end {
|
||||
"stop" => Finish::Stop,
|
||||
"length" => Finish::Length,
|
||||
_ => {
|
||||
events.push(Err(end.strip_prefix("fail:").unwrap().to_owned()));
|
||||
return events;
|
||||
}
|
||||
};
|
||||
events.push(Ok(Event::Done(done(ids.len() as u64, 9, finish))));
|
||||
events
|
||||
}
|
||||
|
||||
/// A worker that takes one command and answers it with `events`, buffered or streamed.
|
||||
fn answer_once(
|
||||
mut received: mpsc::Receiver<GenerationCommand>,
|
||||
events: Vec<Result<Event, String>>,
|
||||
) -> tokio::task::JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let command = received.recv().await.unwrap();
|
||||
match command.result {
|
||||
GenerationResult::Finished => panic!("unexpected finished command"),
|
||||
GenerationResult::Buffered(sender) => {
|
||||
let _ = sender.send(events.into_iter().collect::<Result<Vec<_>, _>>());
|
||||
}
|
||||
GenerationResult::Streaming(sender) => {
|
||||
for event in events {
|
||||
if sender.send(event).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The ids and timestamps of a capture replaced by fixed text.
|
||||
fn normalize(text: &str) -> String {
|
||||
let ids =
|
||||
regex::Regex::new(r"\b(resp|msg|rs|fc|ctc|call)_[0-9a-f]+_[0-9a-f]+(_[0-9]+)?").unwrap();
|
||||
let times = regex::Regex::new(r#""(created_at|completed_at)":[0-9]+"#).unwrap();
|
||||
let text = ids.replace_all(text, "${1}_ID");
|
||||
times.replace_all(&text, r#""${1}":0"#).into_owned()
|
||||
}
|
||||
|
||||
/// Status, content type and body of a response; a stream is read frame by frame.
|
||||
async fn capture(response: Response) -> String {
|
||||
let status = response.status().as_u16();
|
||||
let kind = response
|
||||
.headers()
|
||||
.get("content-type")
|
||||
.and_then(|value| value.to_str().ok());
|
||||
let head = format!("{status} {}\n", kind.unwrap_or(""));
|
||||
let mut body = response.into_body();
|
||||
let mut text = head;
|
||||
while let Some(frame) = body.frame().await {
|
||||
text.push_str(&String::from_utf8_lossy(
|
||||
&frame.unwrap().into_data().unwrap(),
|
||||
));
|
||||
}
|
||||
normalize(&text)
|
||||
}
|
||||
|
||||
/// The capture of one case in one mode.
|
||||
async fn run_case(case: &Value, stream: bool, codecs: &Codecs) -> String {
|
||||
let (mut state, received) = ready_state(&codecs.qwen).await;
|
||||
if case["family"] == "gptoss" {
|
||||
state.model.tokenizer = Some(codecs.gptoss.clone() as Arc<dyn TextCodec>);
|
||||
}
|
||||
let events = worker_events(&script_ids(case, codecs), case["end"].as_str().unwrap());
|
||||
let worker = answer_once(received, events);
|
||||
let mut payload =
|
||||
json!({"model": "strata-local", "input": "test", "stream": stream, "store": false});
|
||||
payload
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(case["request"].as_object().unwrap().clone());
|
||||
let text = capture(create(State(state), Ok(Json(payload))).await).await;
|
||||
worker.await.unwrap();
|
||||
text
|
||||
}
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/fixtures/golden")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
/// Every case in both modes, as `<name>/stream` and `<name>/buffered`.
|
||||
async fn capture_all() -> Vec<(String, String)> {
|
||||
let cases: Value =
|
||||
serde_json::from_str(&fs::read_to_string(fixture("output_cases.json")).unwrap()).unwrap();
|
||||
let (qwen, root) = super::fixtures::test_tokenizer();
|
||||
let gptoss = Arc::new(GptOssCodec::new(gptoss_vocabulary()).unwrap());
|
||||
let codecs = Codecs {
|
||||
qwen,
|
||||
gptoss,
|
||||
gptoss_vocabulary: gptoss_vocabulary(),
|
||||
};
|
||||
let mut captures = Vec::new();
|
||||
for case in cases.as_array().unwrap() {
|
||||
for (mode, stream) in [("stream", true), ("buffered", false)] {
|
||||
let name = format!("{}/{mode}", case["name"].as_str().unwrap());
|
||||
captures.push((name, run_case(case, stream, &codecs).await));
|
||||
}
|
||||
}
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
captures
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn gateway_answers_for_scripted_output_match_the_recorded_golden() {
|
||||
let golden: Value =
|
||||
serde_json::from_str(&fs::read_to_string(fixture("output_events.json")).unwrap()).unwrap();
|
||||
let captures = capture_all().await;
|
||||
assert_eq!(
|
||||
captures.len(),
|
||||
golden.as_object().unwrap().len(),
|
||||
"case count"
|
||||
);
|
||||
for (name, actual) in captures {
|
||||
assert_eq!(golden[&name].as_str(), Some(actual.as_str()), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites the expected captures from the current code. Only for a deliberate change of the gateway output.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "regenerates tests/fixtures/golden/output_events.json"]
|
||||
async fn regenerate_output_golden() {
|
||||
let mut golden = serde_json::Map::new();
|
||||
for (name, text) in capture_all().await {
|
||||
golden.insert(name, Value::String(text));
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&Value::Object(golden)).unwrap() + "\n";
|
||||
fs::write(fixture("output_events.json"), text).unwrap();
|
||||
}
|
||||
|
||||
/// The captures do not depend on the run: two runs agree.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn output_captures_are_deterministic() {
|
||||
assert_eq!(capture_all().await, capture_all().await);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::super::*;
|
||||
use super::fixtures::{make_request, test_tokenizer};
|
||||
use crate::codec::QwenCodec;
|
||||
use leleka_gateway_domain::output::{AtEndPlan, OutputError, OutputEvent, ReadPlan, output_items};
|
||||
use leleka_gateway_domain::output::{AtEndPlan, OutputError, OutputEvent, output_items};
|
||||
use std::fs;
|
||||
|
||||
/// The events of a generation read at its end, with reasoning on and `tools` as the request's flat declarations.
|
||||
@@ -15,11 +15,12 @@ fn read_events(
|
||||
) -> Result<(Vec<OutputEvent>, Vec<OutputEvent>), OutputError> {
|
||||
let plan = AtEndPlan {
|
||||
reasoning: true,
|
||||
preview: true,
|
||||
tools,
|
||||
recovery: false,
|
||||
keep_raw: false,
|
||||
};
|
||||
let mut decoder = tokenizer.output_decoder(ReadPlan::AtEnd(plan));
|
||||
let mut decoder = tokenizer.at_end_decoder(plan);
|
||||
let mut previews = Vec::new();
|
||||
for id in ids {
|
||||
previews.extend(decoder.push(*id)?);
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::fixtures::{make_request, test_tokenizer};
|
||||
use super::live::{done, drain_sse, finish_stream};
|
||||
use crate::responses::StreamEnv as Env;
|
||||
use http_body_util::BodyExt;
|
||||
use leleka_gateway_domain::output::drain_utf8;
|
||||
use leleka_gateway_domain::output::{LivePlan, OutputEvent};
|
||||
use std::fs;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
@@ -92,11 +92,29 @@ async fn token_budget_terminates_live_stream_as_incomplete() {
|
||||
|
||||
#[test]
|
||||
fn utf8_deltas_wait_for_complete_character_and_match_lossy_decode() {
|
||||
let mut pending = Vec::new();
|
||||
pending.extend_from_slice(&[0xe2, 0x82]);
|
||||
assert_eq!(drain_utf8(&mut pending, false), "");
|
||||
pending.push(0xac);
|
||||
assert_eq!(drain_utf8(&mut pending, false), "€");
|
||||
pending.extend_from_slice(&[0xf0, 0x9f]);
|
||||
assert_eq!(drain_utf8(&mut pending, true), "�");
|
||||
let (tokenizer, root) = test_tokenizer();
|
||||
let plan = LivePlan {
|
||||
tools: None,
|
||||
recovery: false,
|
||||
keep_raw: false,
|
||||
};
|
||||
let mut decoder = tokenizer.live_decoder(plan).unwrap();
|
||||
let texts = |events: Vec<OutputEvent>| -> Vec<String> {
|
||||
events
|
||||
.into_iter()
|
||||
.filter_map(|event| match event {
|
||||
OutputEvent::Text(text) => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// the euro sign is three byte tokens: nothing is published before the third
|
||||
assert!(texts(decoder.push(0xe2).unwrap()).is_empty());
|
||||
assert!(texts(decoder.push(0x82).unwrap()).is_empty());
|
||||
assert_eq!(texts(decoder.push(0xac).unwrap()), ["\u{20ac}"]);
|
||||
// a character still cut when the generation ends becomes the replacement character
|
||||
assert!(texts(decoder.push(0xf0).unwrap()).is_empty());
|
||||
assert!(texts(decoder.push(0x9f).unwrap()).is_empty());
|
||||
assert_eq!(texts(decoder.finish(Finish::Length).unwrap()), ["\u{fffd}"]);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_gateway_domain::output::{AtEndPlan, OutputDecoder, OutputError, OutputEvent};
|
||||
use leleka_gateway_domain::output::{AtEndDecoder, AtEndPlan, OutputError, OutputEvent};
|
||||
|
||||
/// EXPERIMENTAL `tool_call_recovery` (config key or `STRATA_TOOL_CALL_RECOVERY`): off unless `main` turns it on at
|
||||
/// start.
|
||||
@@ -20,10 +20,16 @@ pub(super) fn tool_call_recovery() -> bool {
|
||||
TOOL_CALL_RECOVERY.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// What the reading at the end of a generation needs for this request and model family.
|
||||
pub(super) fn at_end_plan<C: TextCodec + ?Sized>(request: &CreateRequest, codec: &C) -> AtEndPlan {
|
||||
/// What the reading at the end of a generation needs for this request and model family; `preview`: somebody watches
|
||||
/// the reasoning arrive.
|
||||
pub(super) fn at_end_plan<C: TextCodec + ?Sized>(
|
||||
request: &CreateRequest,
|
||||
codec: &C,
|
||||
preview: bool,
|
||||
) -> AtEndPlan {
|
||||
AtEndPlan {
|
||||
reasoning: reasoning_enabled(request, codec),
|
||||
preview,
|
||||
tools: (!request.tools.is_empty()).then(|| flat_tools(request)),
|
||||
recovery: tool_call_recovery(),
|
||||
keep_raw: debug_failed_output(),
|
||||
@@ -32,8 +38,8 @@ pub(super) fn at_end_plan<C: TextCodec + ?Sized>(request: &CreateRequest, codec:
|
||||
|
||||
/// End the generation and log what was accepted beyond the template form; a refused call is logged with the
|
||||
/// debug copy of the output when `STRATA_DEBUG_FAILED_OUTPUT` is on.
|
||||
pub(super) fn finish_output(
|
||||
decoder: &mut OutputDecoder<'_>,
|
||||
pub(super) fn finish_generation(
|
||||
decoder: &mut AtEndDecoder,
|
||||
finish: Finish,
|
||||
) -> Result<Vec<OutputEvent>, OutputError> {
|
||||
let events = decoder.finish(finish);
|
||||
@@ -57,40 +63,8 @@ fn log_failed_output(split: Option<(Option<&str>, &str)>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How tool calls are read: `natural_stop` as the generation ended, recovery as configured.
|
||||
#[cfg(test)]
|
||||
pub(super) fn tool_options(natural_stop: bool) -> tool_output::Options {
|
||||
tool_output::Options {
|
||||
natural_stop,
|
||||
recovery: tool_call_recovery(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn parse_output_items(
|
||||
request: &CreateRequest,
|
||||
output: String,
|
||||
id: &str,
|
||||
) -> Result<Vec<OutputItem>, String> {
|
||||
parse_output_items_after(request, output, id, false)
|
||||
}
|
||||
|
||||
/// `natural_stop`: the generation ended by itself and not at the token limit, so a call that ends the text on
|
||||
/// `</function>` is whole.
|
||||
#[cfg(test)]
|
||||
pub(super) fn parse_output_items_after(
|
||||
request: &CreateRequest,
|
||||
output: String,
|
||||
id: &str,
|
||||
natural_stop: bool,
|
||||
) -> Result<Vec<OutputItem>, String> {
|
||||
let (items, notes) = parse_output_items_with(request, output, id, tool_options(natural_stop))?;
|
||||
log_tool_notes(¬es);
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
/// A tool call that was accepted although the template form was not followed is never silent: it is logged here.
|
||||
pub(super) fn log_tool_notes(notes: &tool_output::Notes) {
|
||||
pub(super) fn log_tool_notes(notes: &crate::tool_output::Notes) {
|
||||
if !notes.is_empty() {
|
||||
crate::elog!("tool call accepted beyond the template form ({notes})");
|
||||
}
|
||||
|
||||
+2302
File diff suppressed because it is too large
Load Diff
+295
-109
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
08afbf216
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Running a case through the real `create` handler and reading what a client would read.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{Json, extract::State, response::Response};
|
||||
use http_body_util::BodyExt;
|
||||
use leleka_sampler_ref::RequestSampling;
|
||||
use serde_json::{Value, json};
|
||||
use strata_control::{
|
||||
adapters::ChannelEngine,
|
||||
app::AppState,
|
||||
codec::TextCodec,
|
||||
responses::{create, set_tool_call_recovery},
|
||||
wire::Event,
|
||||
worker::{GenerationCommand, GenerationResult, WorkerState},
|
||||
};
|
||||
use tokio::{sync::mpsc, task::JoinHandle};
|
||||
|
||||
use crate::{
|
||||
script::{Case, worker_events},
|
||||
vocab::Codecs,
|
||||
};
|
||||
|
||||
/// An application state whose worker is ready and whose engine hands every command to the returned receiver.
|
||||
pub async fn ready_state(
|
||||
codecs: &Codecs,
|
||||
gptoss: bool,
|
||||
) -> (AppState, mpsc::Receiver<GenerationCommand>) {
|
||||
let (commands, received) = mpsc::channel::<GenerationCommand>(1);
|
||||
let mut state = AppState::default();
|
||||
state.engine.worker.write().await.state = WorkerState::Ready;
|
||||
let codec: Arc<dyn TextCodec> = if gptoss {
|
||||
codecs.gptoss.clone()
|
||||
} else {
|
||||
codecs.qwen.clone()
|
||||
};
|
||||
state.model.tokenizer = Some(codec);
|
||||
state.engine.client = Some(ChannelEngine::shared(commands));
|
||||
(state, received)
|
||||
}
|
||||
|
||||
/// A worker that takes one command and answers it with `events`, buffered or streamed; it reports the sampling it was
|
||||
/// asked for.
|
||||
pub fn answer_once(
|
||||
mut received: mpsc::Receiver<GenerationCommand>,
|
||||
events: Vec<Result<Event, String>>,
|
||||
) -> JoinHandle<RequestSampling> {
|
||||
tokio::spawn(async move {
|
||||
let command = received.recv().await.unwrap();
|
||||
let sampling = command.request.sampling.clone();
|
||||
match command.result {
|
||||
GenerationResult::Finished => panic!("unexpected finished command"),
|
||||
GenerationResult::Buffered(sender) => {
|
||||
let _ = sender.send(events.into_iter().collect::<Result<Vec<_>, _>>());
|
||||
}
|
||||
GenerationResult::Streaming(sender) => {
|
||||
for event in events {
|
||||
if sender.send(event).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sampling
|
||||
})
|
||||
}
|
||||
|
||||
/// The ids replaced by `<kind>_ID<k>`, `k` counting the distinct ids by first appearance, the numeric suffix kept
|
||||
/// (`call_ID3_1`); the timestamps replaced by 0.
|
||||
pub fn normalize(text: &str) -> String {
|
||||
let ids =
|
||||
regex::Regex::new(r"\b(resp|msg|rs|fc|ctc|call)_[0-9a-f]+_[0-9a-f]+(_[0-9]+)?").unwrap();
|
||||
let times = regex::Regex::new(r#""(created_at|completed_at)":[0-9]+"#).unwrap();
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
let text = ids.replace_all(text, |found: ®ex::Captures| {
|
||||
let id = found[0].to_owned();
|
||||
let k = seen
|
||||
.iter()
|
||||
.position(|known| *known == id)
|
||||
.unwrap_or_else(|| {
|
||||
seen.push(id);
|
||||
seen.len() - 1
|
||||
});
|
||||
format!(
|
||||
"{}_ID{}{}",
|
||||
&found[1],
|
||||
k,
|
||||
found.get(2).map_or("", |suffix| suffix.as_str())
|
||||
)
|
||||
});
|
||||
times.replace_all(&text, r#""${1}":0"#).into_owned()
|
||||
}
|
||||
|
||||
/// Status, content type and body of a response, as sent; a stream is read frame by frame.
|
||||
pub async fn read_response(response: Response) -> String {
|
||||
let status = response.status().as_u16();
|
||||
let kind = response
|
||||
.headers()
|
||||
.get("content-type")
|
||||
.and_then(|value| value.to_str().ok());
|
||||
let mut text = format!("{status} {}\n", kind.unwrap_or(""));
|
||||
let mut body = response.into_body();
|
||||
while let Some(frame) = body.frame().await {
|
||||
text.push_str(&String::from_utf8_lossy(
|
||||
&frame.unwrap().into_data().unwrap(),
|
||||
));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// What a client reads, with the volatile parts replaced.
|
||||
pub async fn capture(response: Response) -> String {
|
||||
normalize(&read_response(response).await)
|
||||
}
|
||||
|
||||
/// The request body of a case in one mode.
|
||||
pub fn payload(case: &Case, stream: bool) -> Value {
|
||||
let mut payload =
|
||||
json!({"model": "strata-local", "input": "test", "stream": stream, "store": false});
|
||||
payload
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(case.request.as_object().unwrap().clone());
|
||||
payload
|
||||
}
|
||||
|
||||
/// The capture of one case in one mode.
|
||||
pub async fn run_case(case: &Case, stream: bool, codecs: &Codecs) -> String {
|
||||
let (state, received) = ready_state(codecs, case.gptoss).await;
|
||||
let worker = answer_once(received, worker_events(case, codecs));
|
||||
set_tool_call_recovery(case.recovery);
|
||||
let response = create(State(state), Ok(Json(payload(case, stream)))).await;
|
||||
let text = capture(response).await;
|
||||
set_tool_call_recovery(false);
|
||||
worker.await.unwrap();
|
||||
text
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
//! What the golden captures cannot show: when the first bytes arrive, and what the gateway does when the client leaves.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::{Json, body::Body, extract::State};
|
||||
use http_body_util::BodyExt;
|
||||
use serde_json::{Value, json};
|
||||
use strata_control::{
|
||||
responses::create,
|
||||
wire::{Event, Finish},
|
||||
worker::{GenerationCommand, GenerationResult},
|
||||
};
|
||||
use tokio::{sync::mpsc, sync::oneshot, task::JoinHandle};
|
||||
|
||||
use crate::{
|
||||
ONE_AT_A_TIME,
|
||||
capture::{read_response, ready_state},
|
||||
script::{Case, done_event, script_ids, token_events, worker_events},
|
||||
vocab::Codecs,
|
||||
};
|
||||
|
||||
/// A worker that sends `ids`, waits for `gate`, then sends the `DONE` of a stop.
|
||||
fn gated_worker(
|
||||
mut received: mpsc::Receiver<GenerationCommand>,
|
||||
ids: Vec<u32>,
|
||||
gate: oneshot::Receiver<()>,
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let command = received.recv().await.unwrap();
|
||||
let GenerationResult::Streaming(sender) = command.result else {
|
||||
panic!("a stream was asked for");
|
||||
};
|
||||
for event in token_events(&ids) {
|
||||
sender.send(event).await.unwrap();
|
||||
}
|
||||
gate.await.unwrap();
|
||||
let done = Event::Done(done_event(ids.len() as u64, Finish::Stop));
|
||||
sender.send(Ok(done)).await.unwrap();
|
||||
})
|
||||
}
|
||||
|
||||
/// Frames up to and including the first one that contains `needle`, each read within five seconds.
|
||||
async fn read_until(body: &mut Body, needle: &str) -> String {
|
||||
let mut text = String::new();
|
||||
while !text.contains(needle) {
|
||||
let frame = tokio::time::timeout(Duration::from_secs(5), body.frame()).await;
|
||||
let frame = frame
|
||||
.expect("no frame within five seconds")
|
||||
.expect("the stream ended")
|
||||
.unwrap();
|
||||
text.push_str(&String::from_utf8_lossy(&frame.into_data().unwrap()));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn named(name: &str) -> Case {
|
||||
crate::cases()
|
||||
.into_iter()
|
||||
.find(|case| case.name == name)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The reasoning is shown while the generation runs, before the worker reports `DONE`.
|
||||
async fn assert_reasoning_arrives_before_done(name: &str, needle: &str) {
|
||||
let codecs = Codecs::new();
|
||||
let case = named(name);
|
||||
let (state, received) = ready_state(&codecs, case.gptoss).await;
|
||||
let (open, gate) = oneshot::channel();
|
||||
let worker = gated_worker(received, script_ids(&case, &codecs), gate);
|
||||
let response = create(State(state), Ok(Json(crate::capture::payload(&case, true)))).await;
|
||||
let mut body = response.into_body();
|
||||
let shown = read_until(&mut body, needle).await;
|
||||
assert!(
|
||||
!shown.contains("response.completed"),
|
||||
"{name}: the response completed before DONE was sent"
|
||||
);
|
||||
open.send(()).unwrap();
|
||||
let rest = read_until(&mut body, "response.completed").await;
|
||||
assert!(rest.contains("response.completed"), "{name}");
|
||||
worker.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reasoning_text_is_streamed_before_the_worker_is_done() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
assert_reasoning_arrives_before_done("q-think-answer", "response.reasoning_text.delta").await;
|
||||
assert_reasoning_arrives_before_done("g-analysis-final", "response.reasoning_text.delta").await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plain_text_and_whole_calls_are_streamed_before_the_worker_is_done() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
assert_reasoning_arrives_before_done("q-text", "response.output_text.delta").await;
|
||||
assert_reasoning_arrives_before_done("q-tools-call", "response.function_call_arguments.done")
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A client that leaves closes the source of the worker's events, in every mode of the stream.
|
||||
async fn assert_source_closed_after_disconnect(name: &str) {
|
||||
let codecs = Codecs::new();
|
||||
let case = named(name);
|
||||
let (state, mut received) = ready_state(&codecs, case.gptoss).await;
|
||||
let watcher = tokio::spawn(async move {
|
||||
let command = received.recv().await.unwrap();
|
||||
let GenerationResult::Streaming(sender) = command.result else {
|
||||
panic!("a stream was asked for");
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(3), sender.closed())
|
||||
.await
|
||||
.is_ok()
|
||||
});
|
||||
let response = create(State(state), Ok(Json(crate::capture::payload(&case, true)))).await;
|
||||
let mut body = response.into_body();
|
||||
let _ = read_until(&mut body, "response.created").await;
|
||||
drop(body);
|
||||
assert!(
|
||||
watcher.await.unwrap(),
|
||||
"{name}: the source stayed open after the client left"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_client_that_leaves_closes_the_source_in_every_stream_mode() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
for name in [
|
||||
"q-text",
|
||||
"q-tools-call",
|
||||
"q-structured-valid",
|
||||
"q-think-answer",
|
||||
"g-analysis-final",
|
||||
] {
|
||||
assert_source_closed_after_disconnect(name).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The 400 a gpt-oss request gets when its body also carries `extra`.
|
||||
async fn refusal_for(extra: serde_json::Value, codecs: &Codecs) -> String {
|
||||
let case = named("g-final-only");
|
||||
let (state, _received) = ready_state(codecs, true).await;
|
||||
let mut body = crate::capture::payload(&case, false);
|
||||
body.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(extra.as_object().unwrap().clone());
|
||||
crate::capture::capture(create(State(state), Ok(Json(body))).await).await
|
||||
}
|
||||
|
||||
/// The first sampler of the request that the gpt-oss worker lacks is named in a 400 before any engine work.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_sampler_the_gptoss_worker_lacks_is_refused_and_named() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let codecs = Codecs::new();
|
||||
let refused = [
|
||||
(json!({"top_k": 5}), "top_k"),
|
||||
(json!({"min_p": 0.1}), "min_p"),
|
||||
(json!({"repetition_penalty": 1.2}), "repetition_penalty"),
|
||||
(json!({"frequency_penalty": 0.5}), "frequency_penalty"),
|
||||
(json!({"presence_penalty": 0.5}), "presence_penalty"),
|
||||
(json!({"min_p": 0.1, "top_k": 5}), "top_k"),
|
||||
];
|
||||
for (extra, param) in refused {
|
||||
let text = refusal_for(extra, &codecs).await;
|
||||
assert!(text.starts_with("400 "), "{param}: {text}");
|
||||
assert!(
|
||||
text.contains(&format!("\"param\":\"{param}\"")),
|
||||
"{param}: {text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains("supports temperature, top_p and seed only"),
|
||||
"{param}: {text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `response` of the `response.completed` event of a stream, as the client read it (not normalised).
|
||||
fn completed_response(stream: &str) -> Value {
|
||||
let data = stream
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data: "));
|
||||
let events = data.map(|data| serde_json::from_str::<Value>(data).unwrap());
|
||||
let mut events = events;
|
||||
events
|
||||
.find(|event| event["type"] == "response.completed")
|
||||
.unwrap()["response"]
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// A stored response is the one the client was sent, streamed or not.
|
||||
async fn assert_stored_copy_equals_the_sent_one(name: &str, stream: bool) {
|
||||
let codecs = Codecs::new();
|
||||
let case = named(name);
|
||||
let (state, received) = ready_state(&codecs, case.gptoss).await;
|
||||
let worker = crate::capture::answer_once(received, worker_events(&case, &codecs));
|
||||
let mut body = crate::capture::payload(&case, stream);
|
||||
body["store"] = json!(true);
|
||||
let sent = read_response(create(State(state.clone()), Ok(Json(body))).await).await;
|
||||
worker.await.unwrap();
|
||||
let sent = if stream {
|
||||
completed_response(&sent)
|
||||
} else {
|
||||
serde_json::from_str(sent.split_once('\n').unwrap().1).unwrap()
|
||||
};
|
||||
let id = sent["id"].as_str().unwrap().to_owned();
|
||||
let stored = state.services.responses.response(&id).await;
|
||||
assert_eq!(stored, Some(sent), "{name} stream={stream}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_stored_response_is_the_one_the_client_was_sent() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
for name in [
|
||||
"q-text",
|
||||
"q-tools-call",
|
||||
"q-think-answer",
|
||||
"q-structured-valid",
|
||||
"g-call",
|
||||
"g-analysis-final",
|
||||
] {
|
||||
for stream in [true, false] {
|
||||
assert_stored_copy_equals_the_sent_one(name, stream).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A client that leaves after the worker's `DONE` (while the response is read, or its last reasoning flushed) does not
|
||||
/// leave the stream running: the source is closed once the stream is over.
|
||||
async fn assert_source_closed_after_disconnect_at_done(name: &str) {
|
||||
let codecs = Codecs::new();
|
||||
let case = named(name);
|
||||
let (state, mut received) = ready_state(&codecs, case.gptoss).await;
|
||||
let events = worker_events(&case, &codecs);
|
||||
let watcher = tokio::spawn(async move {
|
||||
let command = received.recv().await.unwrap();
|
||||
let GenerationResult::Streaming(sender) = command.result else {
|
||||
panic!("a stream was asked for");
|
||||
};
|
||||
for event in events {
|
||||
let _ = sender.send(event).await;
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(3), sender.closed())
|
||||
.await
|
||||
.is_ok()
|
||||
});
|
||||
let response = create(State(state), Ok(Json(crate::capture::payload(&case, true)))).await;
|
||||
let mut body = response.into_body();
|
||||
let _ = read_until(&mut body, "response.created").await;
|
||||
drop(body);
|
||||
assert!(
|
||||
watcher.await.unwrap(),
|
||||
"{name}: the source stayed open after the client left"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_client_that_leaves_at_done_closes_the_source() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let names = [
|
||||
"q-think-unclosed-length",
|
||||
"q-think-answer",
|
||||
"q-structured-valid",
|
||||
"q-tools-call",
|
||||
"g-analysis-cut-length",
|
||||
];
|
||||
for name in names {
|
||||
assert_source_closed_after_disconnect_at_done(name).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Golden captures of what the gateway answers for a scripted model output, for both families (STRA-338 S23).
|
||||
//!
|
||||
//! A scripted worker answers the real `create` handler with a fixed token sequence, once as a stream and once as a
|
||||
//! buffered answer. The bytes the client would read (status, content type, SSE frames or the JSON body) are stored
|
||||
//! after the volatile parts (ids made of the clock and a counter, timestamps) are replaced. The scripts are in
|
||||
//! `tests/fixtures/golden/output_cases.json`, the expected captures in `output_events.json`. The captures were recorded
|
||||
//! on the code before the output decoding moved behind `OutputEvent`; a difference is a bug of the new code, never a
|
||||
//! reason to record again. All scripts are synthetic: no capture of a real session is committed.
|
||||
//!
|
||||
//! This is its own test binary: the cases switch the process-wide tool-call recovery, so nothing else may run beside
|
||||
//! them, and the tests of this file take a lock.
|
||||
|
||||
mod capture;
|
||||
mod live;
|
||||
mod sampling;
|
||||
mod script;
|
||||
mod vocab;
|
||||
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use serde_json::Value;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use capture::{normalize, run_case};
|
||||
use script::{Case, load_cases};
|
||||
use vocab::Codecs;
|
||||
|
||||
/// One test at a time: the recovery switch is process-wide.
|
||||
static ONE_AT_A_TIME: Mutex<()> = Mutex::const_new(());
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/fixtures/golden")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
load_cases(&fs::read_to_string(fixture("output_cases.json")).unwrap())
|
||||
}
|
||||
|
||||
/// Every case in both modes, as `<name>/stream` and `<name>/buffered`.
|
||||
async fn capture_all(codecs: &Codecs) -> Vec<(String, String)> {
|
||||
let mut captures = Vec::new();
|
||||
for case in cases() {
|
||||
for (mode, stream) in [("stream", true), ("buffered", false)] {
|
||||
let capture = run_case(&case, stream, codecs).await;
|
||||
captures.push((format!("{}/{mode}", case.name), capture));
|
||||
}
|
||||
}
|
||||
captures
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn gateway_answers_for_scripted_output_match_the_recorded_golden() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let golden: Value =
|
||||
serde_json::from_str(&fs::read_to_string(fixture("output_events.json")).unwrap()).unwrap();
|
||||
let captures = capture_all(&Codecs::new()).await;
|
||||
assert_eq!(
|
||||
captures.len(),
|
||||
golden.as_object().unwrap().len(),
|
||||
"case count"
|
||||
);
|
||||
for (name, actual) in captures {
|
||||
assert_eq!(golden[&name].as_str(), Some(actual.as_str()), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The commit the expected captures were recorded on: the code before the output decoding moved behind `OutputEvent`.
|
||||
const RECORDED_ON: &str = "08afbf216";
|
||||
|
||||
/// Recording is refused on code that has the output module: a changed code must never pass by recording its own
|
||||
/// captures. Set `OUTPUT_GOLDEN_RECORD` to the commit of the pre-S23 tree the test runs in.
|
||||
fn assert_recording_is_allowed() {
|
||||
let commit = std::env::var("OUTPUT_GOLDEN_RECORD")
|
||||
.expect("set OUTPUT_GOLDEN_RECORD to the commit recorded on");
|
||||
assert!(
|
||||
commit.starts_with(RECORDED_ON),
|
||||
"the golden is recorded on {RECORDED_ON}, not {commit}"
|
||||
);
|
||||
let output =
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../crates/gateway-domain/src/output.rs");
|
||||
assert!(
|
||||
!output.exists(),
|
||||
"this tree has the output module: record on {RECORDED_ON}, not on it"
|
||||
);
|
||||
}
|
||||
|
||||
/// Rewrites the expected captures. Only for recording on the code before the change, never to make changed code pass.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "records tests/fixtures/golden/output_events.json on the code before S23 (OUTPUT_GOLDEN_RECORD)"]
|
||||
async fn regenerate_output_golden() {
|
||||
assert_recording_is_allowed();
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let mut golden = serde_json::Map::new();
|
||||
for (name, text) in capture_all(&Codecs::new()).await {
|
||||
golden.insert(name, Value::String(text));
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&Value::Object(golden)).unwrap() + "\n";
|
||||
fs::write(fixture("output_events.json"), text).unwrap();
|
||||
fs::write(
|
||||
fixture("output_events.recorded_on"),
|
||||
format!("{RECORDED_ON}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_captures_name_the_commit_they_were_recorded_on() {
|
||||
let recorded = fs::read_to_string(fixture("output_events.recorded_on")).unwrap();
|
||||
assert_eq!(recorded.trim(), RECORDED_ON);
|
||||
}
|
||||
|
||||
/// The captures do not depend on the run: two runs agree.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn output_captures_are_deterministic() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let codecs = Codecs::new();
|
||||
assert_eq!(capture_all(&codecs).await, capture_all(&codecs).await);
|
||||
}
|
||||
|
||||
/// The call ids of a buffered capture, in output order.
|
||||
fn call_ids(capture: &str) -> Vec<String> {
|
||||
let body: Value = serde_json::from_str(capture.split_once('\n').unwrap().1).unwrap();
|
||||
let items = body["output"].as_array().unwrap();
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|item| item["call_id"].as_str().map(str::to_owned))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Codex pairs a tool output with its call by `call_id`: two calls of one response must not share one.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn two_calls_of_one_response_have_different_call_ids() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let codecs = Codecs::new();
|
||||
for name in [
|
||||
"q-tools-two-calls",
|
||||
"g-preamble-and-two-calls",
|
||||
"q-think-two-calls",
|
||||
] {
|
||||
let case = cases().into_iter().find(|case| case.name == name).unwrap();
|
||||
let ids = call_ids(&run_case(&case, false, &codecs).await);
|
||||
assert_eq!(ids.len(), 2, "{name}: {ids:?}");
|
||||
assert_ne!(ids[0], ids[1], "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The reasoning tokens of a response end at the token that completed the `</think>` marker.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reasoning_tokens_end_at_the_token_that_completes_the_marker() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let codecs = Codecs::new();
|
||||
for case in cases()
|
||||
.into_iter()
|
||||
.filter(|case| case.reasoning_tokens.is_some())
|
||||
{
|
||||
let body: Value = serde_json::from_str(
|
||||
run_case(&case, false, &codecs)
|
||||
.await
|
||||
.split_once('\n')
|
||||
.unwrap()
|
||||
.1,
|
||||
)
|
||||
.unwrap();
|
||||
let counted = body["usage"]["output_tokens_details"]["reasoning_tokens"].as_u64();
|
||||
assert_eq!(counted, case.reasoning_tokens, "{}", case.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_numbered_by_first_appearance_and_keep_their_suffix() {
|
||||
let text =
|
||||
r#"["resp_1a_2","call_1a_2_0","call_1a_2_1","call_1a_2_0","msg_1a_2_0","created_at":17]"#;
|
||||
let expected =
|
||||
r#"["resp_ID0","call_ID1_0","call_ID2_1","call_ID1_0","msg_ID3_0","created_at":0]"#;
|
||||
assert_eq!(normalize(text), expected);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! What the worker is asked for: the sampling of the request after the server defaults and the model's limit.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{Json, extract::State};
|
||||
use leleka_sampler_ref::RequestSampling;
|
||||
use leleka_serving_policy::shared::ConfigSampling;
|
||||
use serde_json::{Value, json};
|
||||
use strata_control::{responses::create, settings::Settings};
|
||||
|
||||
use crate::{
|
||||
ONE_AT_A_TIME,
|
||||
capture::{answer_once, capture, payload, ready_state},
|
||||
script::worker_events,
|
||||
vocab::Codecs,
|
||||
};
|
||||
|
||||
/// The server defaults of the test: every sampler set.
|
||||
fn busy_defaults() -> ConfigSampling {
|
||||
let sampling = RequestSampling {
|
||||
top_k: Some(20),
|
||||
min_p: Some(0.05),
|
||||
repetition_penalty: Some(1.1),
|
||||
frequency_penalty: Some(0.1),
|
||||
presence_penalty: Some(0.2),
|
||||
penalty_last_n: Some(64),
|
||||
..Default::default()
|
||||
};
|
||||
ConfigSampling {
|
||||
sampling,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer to a request of a case, with `extra` in its body and `defaults` as the server's sampling defaults, and
|
||||
/// the sampling the worker was asked for.
|
||||
async fn ask(
|
||||
name: &str,
|
||||
extra: Value,
|
||||
defaults: Option<ConfigSampling>,
|
||||
) -> (String, RequestSampling) {
|
||||
let codecs = Codecs::new();
|
||||
let case = crate::cases()
|
||||
.into_iter()
|
||||
.find(|case| case.name == name)
|
||||
.unwrap();
|
||||
let (mut state, received) = ready_state(&codecs, case.gptoss).await;
|
||||
if let Some(defaults) = defaults {
|
||||
state.services.settings = Arc::new(Settings::new(defaults));
|
||||
}
|
||||
let worker = answer_once(received, worker_events(&case, &codecs));
|
||||
let mut body = payload(&case, false);
|
||||
body.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(extra.as_object().unwrap().clone());
|
||||
let text = capture(create(State(state), Ok(Json(body))).await).await;
|
||||
(text, worker.await.unwrap())
|
||||
}
|
||||
|
||||
/// gpt-oss takes temperature, top_p and seed: the server defaults for the other samplers do not reach its worker.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_server_defaults_of_samplers_gptoss_lacks_do_not_reach_its_worker() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let (text, sampling) = ask("g-final-only", json!({}), Some(busy_defaults())).await;
|
||||
assert!(text.starts_with("200 "), "{text}");
|
||||
assert_eq!(sampling.top_k, None);
|
||||
assert_eq!(sampling.min_p, None);
|
||||
assert_eq!(sampling.repetition_penalty, None);
|
||||
assert_eq!(sampling.frequency_penalty, None);
|
||||
assert_eq!(sampling.presence_penalty, None);
|
||||
assert_eq!(sampling.penalty_last_n, None);
|
||||
}
|
||||
|
||||
/// A sampler set to its neutral value is not a request for the sampler: it is accepted.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn neutral_values_of_samplers_gptoss_lacks_are_accepted() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let neutral =
|
||||
json!({"repetition_penalty": 1.0, "frequency_penalty": 0.0, "presence_penalty": 0.0});
|
||||
let (text, sampling) = ask("g-final-only", neutral, None).await;
|
||||
assert!(text.starts_with("200 "), "{text}");
|
||||
assert_eq!(sampling.repetition_penalty, None);
|
||||
}
|
||||
|
||||
/// Qwen takes every sampler: the request's and the defaults' reach the worker.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn qwen_keeps_every_sampler_of_the_request_and_the_defaults() {
|
||||
let _one = ONE_AT_A_TIME.lock().await;
|
||||
let (text, sampling) = ask("q-text", json!({}), Some(busy_defaults())).await;
|
||||
assert!(text.starts_with("200 "), "{text}");
|
||||
assert_eq!(sampling.top_k, Some(20));
|
||||
assert_eq!(sampling.min_p, Some(0.05));
|
||||
assert_eq!(sampling.repetition_penalty, Some(1.1));
|
||||
assert_eq!(sampling.frequency_penalty, Some(0.1));
|
||||
assert_eq!(sampling.presence_penalty, Some(0.2));
|
||||
assert_eq!(sampling.penalty_last_n, Some(64));
|
||||
let own = json!({
|
||||
"top_k": 5, "min_p": 0.2, "repetition_penalty": 1.3, "frequency_penalty": 0.4, "presence_penalty": 0.5
|
||||
});
|
||||
let (_, sampling) = ask("q-text", own, Some(busy_defaults())).await;
|
||||
assert_eq!(sampling.top_k, Some(5));
|
||||
assert_eq!(sampling.min_p, Some(0.2));
|
||||
assert_eq!(sampling.repetition_penalty, Some(1.3));
|
||||
assert_eq!(sampling.frequency_penalty, Some(0.4));
|
||||
assert_eq!(sampling.presence_penalty, Some(0.5));
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! A case of `output_cases.json` as the events a scripted worker sends.
|
||||
//!
|
||||
//! A script is a list of parts: `@name` is the special token `name`, `%N` the token with id `N`, `~name` an extra
|
||||
//! token of the vocabulary (see `vocab::EXTRA`), anything else is text as byte-level tokens.
|
||||
|
||||
use serde_json::Value;
|
||||
use strata_control::wire::{Done, Event, Finish};
|
||||
|
||||
use crate::vocab::Codecs;
|
||||
|
||||
/// How the worker's events end.
|
||||
pub enum End {
|
||||
Done(Finish),
|
||||
/// The worker reports a failure after the tokens.
|
||||
Fail(String),
|
||||
/// The worker closes its side after the tokens without a `DONE` or an error.
|
||||
Close,
|
||||
/// The worker reports `DONE` before the first token.
|
||||
DoneFirst,
|
||||
/// The worker reports a failure after the tokens and their `DONE`.
|
||||
ErrorAfterDone(String),
|
||||
}
|
||||
|
||||
pub struct Case {
|
||||
pub name: String,
|
||||
pub gptoss: bool,
|
||||
pub request: Value,
|
||||
pub script: Vec<String>,
|
||||
pub end: End,
|
||||
pub recovery: bool,
|
||||
pub reasoning_tokens: Option<u64>,
|
||||
/// The generated count the worker reports, when it is not the number of tokens sent.
|
||||
pub generated: Option<u64>,
|
||||
}
|
||||
|
||||
fn end_of(word: &str) -> End {
|
||||
match word {
|
||||
"stop" => End::Done(Finish::Stop),
|
||||
"length" => End::Done(Finish::Length),
|
||||
"cancel" => End::Done(Finish::Cancel),
|
||||
"close" => End::Close,
|
||||
"done-first" => End::DoneFirst,
|
||||
other if other.starts_with("error-after-done:") => {
|
||||
End::ErrorAfterDone(other.strip_prefix("error-after-done:").unwrap().to_owned())
|
||||
}
|
||||
other => End::Fail(other.strip_prefix("fail:").unwrap().to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
fn case_of(value: &Value) -> Case {
|
||||
let strings = |key: &str| -> Vec<String> {
|
||||
value[key]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|part| part.as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
};
|
||||
Case {
|
||||
name: value["name"].as_str().unwrap().to_owned(),
|
||||
gptoss: value["family"] == "gptoss",
|
||||
request: value["request"].clone(),
|
||||
script: strings("script"),
|
||||
end: end_of(value["end"].as_str().unwrap()),
|
||||
recovery: value["recovery"].as_bool().unwrap_or(false),
|
||||
reasoning_tokens: value["reasoning_tokens"].as_u64(),
|
||||
generated: value["generated"].as_u64(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every case of the file, in its order.
|
||||
pub fn load_cases(text: &str) -> Vec<Case> {
|
||||
let cases: Value = serde_json::from_str(text).unwrap();
|
||||
cases.as_array().unwrap().iter().map(case_of).collect()
|
||||
}
|
||||
|
||||
fn text_ids(codecs: &Codecs, gptoss: bool, text: &str) -> Vec<u32> {
|
||||
if gptoss {
|
||||
codecs.gptoss_vocabulary.encode(text, false)
|
||||
} else {
|
||||
codecs.qwen.encode(text, false).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn special_id(codecs: &Codecs, gptoss: bool, name: &str) -> u32 {
|
||||
if gptoss {
|
||||
codecs.gptoss_vocabulary.token_id(name).unwrap()
|
||||
} else {
|
||||
codecs.qwen.special_id(name).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// The token ids of a case's script under its family.
|
||||
pub fn script_ids(case: &Case, codecs: &Codecs) -> Vec<u32> {
|
||||
let mut ids = Vec::new();
|
||||
for part in &case.script {
|
||||
if let Some(name) = part.strip_prefix('@') {
|
||||
ids.push(special_id(codecs, case.gptoss, name));
|
||||
} else if let Some(id) = part.strip_prefix('%') {
|
||||
ids.push(id.parse().unwrap());
|
||||
} else if let Some(name) = part.strip_prefix('~') {
|
||||
ids.push(codecs.extra_id(case.gptoss, name));
|
||||
} else {
|
||||
ids.extend(text_ids(codecs, case.gptoss, part));
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
pub fn done_event(generated: u64, finish: Finish) -> Done {
|
||||
Done {
|
||||
generated,
|
||||
prompt_tokens: 9,
|
||||
prompt_ms: 1.0,
|
||||
decode_ms: 2.0,
|
||||
finish,
|
||||
drafts_accepted: None,
|
||||
drafts_offered: None,
|
||||
reused: None,
|
||||
expert_hits: None,
|
||||
expert_lookups: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tokens a worker sends, one event each.
|
||||
pub fn token_events(ids: &[u32]) -> Vec<Result<Event, String>> {
|
||||
ids.iter().map(|id| Ok(Event::Token(*id))).collect()
|
||||
}
|
||||
|
||||
/// The events a worker sends for a case: its tokens and the way they end.
|
||||
pub fn worker_events(case: &Case, codecs: &Codecs) -> Vec<Result<Event, String>> {
|
||||
let ids = script_ids(case, codecs);
|
||||
let mut events = token_events(&ids);
|
||||
let generated = case.generated.unwrap_or(ids.len() as u64);
|
||||
let done = |finish| Ok(Event::Done(done_event(generated, finish)));
|
||||
match &case.end {
|
||||
End::Done(finish) => events.push(done(*finish)),
|
||||
End::Fail(message) => events.push(Err(message.clone())),
|
||||
End::Close => {}
|
||||
End::DoneFirst => events.insert(0, done(Finish::Stop)),
|
||||
End::ErrorAfterDone(message) => {
|
||||
events.push(done(Finish::Stop));
|
||||
events.push(Err(message.clone()));
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//! The two test codecs: a byte-level vocabulary with the family's special tokens and a few multi-byte tokens.
|
||||
//!
|
||||
//! Token ids are the byte values 0..=255. Qwen3.5 continues with its four specials (256..=259), gpt-oss with the eight
|
||||
//! Harmony markers (256..=263); the extra tokens follow, in the order of [`EXTRA`].
|
||||
|
||||
use std::{fs, path::PathBuf, sync::Arc};
|
||||
|
||||
use serde_json::{Map, json};
|
||||
use strata_control::{
|
||||
codec::{QwenCodec, qwen_codec},
|
||||
harmony_family::GptOssCodec,
|
||||
tokenizer::{Tokenizer, byte_alphabet},
|
||||
};
|
||||
|
||||
/// Extra tokens: a name for the scripts and the bytes the token stands for.
|
||||
pub const EXTRA: [(&str, &[u8]); 5] = [
|
||||
("euro", "\u{20ac}".as_bytes()),
|
||||
("grin", "\u{1f600}".as_bytes()),
|
||||
("eacute_end", "\u{e9}</think>".as_bytes()),
|
||||
("mid_open", b"x</thi"),
|
||||
("mid_close", b"nk>y"),
|
||||
];
|
||||
|
||||
const QWEN_SPECIALS: [&str; 4] = ["<|im_start|>", "<|im_end|>", "<think>", "</think>"];
|
||||
const OSS_MARKERS: [&str; 8] = [
|
||||
"<|start|>",
|
||||
"<|end|>",
|
||||
"<|message|>",
|
||||
"<|channel|>",
|
||||
"<|call|>",
|
||||
"<|return|>",
|
||||
"<|constrain|>",
|
||||
"<|endoftext|>",
|
||||
];
|
||||
|
||||
/// The codecs of both families and what a script needs to name their tokens.
|
||||
pub struct Codecs {
|
||||
pub qwen: Arc<QwenCodec>,
|
||||
pub gptoss: Arc<GptOssCodec>,
|
||||
pub gptoss_vocabulary: leleka_tokenizer::gguf_bpe::GgufBpe,
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for Codecs {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte-alphabet spelling of `bytes`, which is how a vocabulary file names a token.
|
||||
fn spell(bytes: &[u8]) -> String {
|
||||
let alphabet = byte_alphabet().0;
|
||||
bytes.iter().map(|byte| alphabet[*byte as usize]).collect()
|
||||
}
|
||||
|
||||
/// The Qwen vocabulary: the byte tokens, the four specials, the extra tokens; `vocab.json` as a map.
|
||||
fn qwen_vocabulary() -> Map<String, serde_json::Value> {
|
||||
let mut vocabulary = Map::new();
|
||||
for (id, ch) in byte_alphabet().0.iter().enumerate() {
|
||||
vocabulary.insert(ch.to_string(), json!(id));
|
||||
}
|
||||
for (offset, token) in QWEN_SPECIALS.iter().enumerate() {
|
||||
vocabulary.insert((*token).into(), json!(256 + offset));
|
||||
}
|
||||
for (offset, (_, bytes)) in EXTRA.iter().enumerate() {
|
||||
vocabulary.insert(spell(bytes), json!(256 + QWEN_SPECIALS.len() + offset));
|
||||
}
|
||||
vocabulary
|
||||
}
|
||||
|
||||
fn write_json(root: &std::path::Path, name: &str, value: &impl serde::Serialize) {
|
||||
fs::write(root.join(name), serde_json::to_vec(value).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
fn write_qwen_assets(root: &std::path::Path) {
|
||||
let vocabulary = qwen_vocabulary();
|
||||
let size = vocabulary.len();
|
||||
let mut types = vec![1u8; size];
|
||||
types[256..256 + QWEN_SPECIALS.len()].fill(3);
|
||||
let metadata = json!({
|
||||
"model": "gpt2", "pre": "qwen35", "vocab_size": size, "n_merges": 0,
|
||||
"pre_pattern": leleka_tokenizer::QWEN35_PATTERN,
|
||||
"special_ids": {"tokenizer.ggml.eos_token_id": 257}
|
||||
});
|
||||
write_json(root, "vocab.json", &vocabulary);
|
||||
fs::write(root.join("merges.txt"), "").unwrap();
|
||||
write_json(root, "token_type.json", &types);
|
||||
write_json(root, "tokenizer.json", &metadata);
|
||||
}
|
||||
|
||||
/// The gpt-oss vocabulary: the byte tokens, the Harmony markers as control tokens, the extra tokens.
|
||||
fn gptoss_vocabulary() -> leleka_tokenizer::gguf_bpe::GgufBpe {
|
||||
let mut tokens: Vec<String> = byte_alphabet().0.iter().map(|c| c.to_string()).collect();
|
||||
let mut types = vec![1i64; 256];
|
||||
for marker in OSS_MARKERS {
|
||||
tokens.push(marker.to_owned());
|
||||
types.push(3);
|
||||
}
|
||||
for (_, bytes) in EXTRA {
|
||||
tokens.push(spell(bytes));
|
||||
types.push(1);
|
||||
}
|
||||
let parts: Vec<&str> = tokens.iter().map(String::as_str).collect();
|
||||
leleka_tokenizer::gguf_bpe::GgufBpe::from_parts(&parts, &types, &[], None, None, None).unwrap()
|
||||
}
|
||||
|
||||
impl Codecs {
|
||||
pub fn new() -> Self {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("strata-output-golden-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
write_qwen_assets(&root);
|
||||
let qwen = Arc::new(qwen_codec(Tokenizer::from_assets(&root).unwrap()));
|
||||
let gptoss = Arc::new(GptOssCodec::new(gptoss_vocabulary()).unwrap());
|
||||
Self {
|
||||
qwen,
|
||||
gptoss,
|
||||
gptoss_vocabulary: gptoss_vocabulary(),
|
||||
root,
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of extra token `name` under a family.
|
||||
pub fn extra_id(&self, gptoss: bool, name: &str) -> u32 {
|
||||
let index = EXTRA.iter().position(|(extra, _)| *extra == name).unwrap();
|
||||
let base = if gptoss {
|
||||
256 + OSS_MARKERS.len()
|
||||
} else {
|
||||
256 + QWEN_SPECIALS.len()
|
||||
};
|
||||
(base + index) as u32
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
//! Every ported Qwen specimen is read as listed, whole and streamed.
|
||||
|
||||
use serde_json::Value;
|
||||
use strata_control::tool_output::{Incremental, Options, Segment, calls_at_end, parse_with};
|
||||
use strata_control::{
|
||||
tool_output::{Incremental, Options, Segment, parse_with},
|
||||
wire::Finish,
|
||||
};
|
||||
|
||||
struct Specimen {
|
||||
name: String,
|
||||
@@ -61,32 +64,22 @@ struct Seen {
|
||||
reasoning: String,
|
||||
}
|
||||
|
||||
/// What the reading at the end (`leleka_gateway_domain::output`, `at_end.rs`) does with the bytes of a reasoning
|
||||
/// request (kept in step with it by hand).
|
||||
/// The reasoning and the answer of a specimen, cut as the gateway cuts a generation that started in reasoning.
|
||||
fn split_reasoning(spec: &Specimen, recovery: bool) -> Result<(String, String), String> {
|
||||
if !spec.thinking {
|
||||
return Ok((String::new(), spec.text.clone()));
|
||||
}
|
||||
match spec.text.find("</think>") {
|
||||
Some(at) => Ok((
|
||||
spec.text[..at].to_owned(),
|
||||
spec.text[at + "</think>".len()..]
|
||||
.trim_start_matches('\n')
|
||||
.to_owned(),
|
||||
)),
|
||||
None if spec.length => Ok((spec.text.clone(), String::new())),
|
||||
None => match calls_at_end(
|
||||
&spec.text,
|
||||
&spec.tools,
|
||||
Options {
|
||||
natural_stop: false,
|
||||
recovery,
|
||||
},
|
||||
) {
|
||||
Some(at) => Ok((spec.text[..at].to_owned(), spec.text[at..].to_owned())),
|
||||
None => Err("reasoning ended without </think>".into()),
|
||||
},
|
||||
}
|
||||
let finish = if spec.length {
|
||||
Finish::Length
|
||||
} else {
|
||||
Finish::Stop
|
||||
};
|
||||
leleka_gateway_domain::output::cut_reasoning_for_corpus(
|
||||
&spec.text,
|
||||
finish,
|
||||
&spec.tools,
|
||||
recovery,
|
||||
)
|
||||
}
|
||||
|
||||
fn seen(reasoning: String, segments: Vec<Segment>) -> Seen {
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
//! The text side of a model family: how prompts become token ids and generated ids become text.
|
||||
//! The text side of a model family: how prompts become token ids and how generated ids become output events.
|
||||
//!
|
||||
//! The Responses code was written for Qwen3.5 (ChatML prompt, `<think>` reasoning, `<tool_call>` XML).
|
||||
//! A family supplies its tokenizer and a stateful decoder that turns the generated token stream into
|
||||
//! that same markup, so the existing reasoning and tool-call parsing, validation, history and streaming
|
||||
//! events work unchanged. For gpt-oss the decoder translates Harmony channels and tool calls
|
||||
//! (see `harmony_family`).
|
||||
//! A family supplies its tokenizer and the decoders (`crate::output`) that turn the generated token stream into
|
||||
//! `OutputEvent`s: reasoning, answer text and whole tool calls. Everything after the decoder is the same for every
|
||||
//! family. For gpt-oss the decoder reads Harmony channels and tool calls (see `harmony_family`).
|
||||
|
||||
use crate::output::{OutputDecoder, ReadPlan};
|
||||
use crate::output::{AtEndDecoder, AtEndPlan, LiveDecoder, LivePlan};
|
||||
use crate::sampler_limit::SamplingLimit;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Which prompt format and output grammar a served model uses.
|
||||
@@ -18,30 +17,24 @@ pub enum Family {
|
||||
GptOss,
|
||||
}
|
||||
|
||||
/// Turns generated token ids into text bytes, keeping whatever state the family's grammar needs.
|
||||
pub trait TokenDecoder: Send {
|
||||
/// The bytes for one more generated token.
|
||||
fn push(&mut self, id: u32) -> Result<Vec<u8>, String>;
|
||||
/// The generation ended: any bytes the decoder was holding back.
|
||||
fn finish(&mut self) -> Vec<u8>;
|
||||
}
|
||||
|
||||
/// Tokenizer and output decoding of one model family.
|
||||
pub trait TextCodec: Send + Sync {
|
||||
fn family(&self) -> Family;
|
||||
/// Token ids of `text`; `parse_special` turns special-token text (the template markers) into tokens.
|
||||
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>;
|
||||
/// The decoder of one generation whose text and calls are published as they complete; `None` for a model that
|
||||
/// always reasons, whose output is read at its end.
|
||||
fn live_decoder<'a>(&self, _plan: LivePlan<'a>) -> Option<LiveDecoder<'a>> {
|
||||
None
|
||||
}
|
||||
/// The decoder of one generation that is read once it has ended.
|
||||
fn at_end_decoder(&self, plan: AtEndPlan) -> AtEndDecoder;
|
||||
/// The model reasons whatever the request's effort says (gpt-oss always opens with its analysis channel).
|
||||
fn always_reasons(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// What the model's worker cannot sample, in the words of the error a client gets for asking for it; `None`: the
|
||||
/// model takes every sampler of the request.
|
||||
fn sampling_limit(&self) -> Option<&'static str> {
|
||||
/// The samplers the model's worker cannot carry; `None`: it takes every sampler of the request.
|
||||
fn sampling_limit(&self) -> Option<SamplingLimit> {
|
||||
None
|
||||
}
|
||||
/// Tokens that end the visible output of a generation (they are not part of the text).
|
||||
@@ -58,30 +51,6 @@ pub trait TextCodec: Send + Sync {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a whole id sequence at once.
|
||||
pub fn decode_all<C: TextCodec + ?Sized>(codec: &C, ids: &[u32]) -> Result<Vec<u8>, String> {
|
||||
let mut decoder = codec.decoder();
|
||||
let mut bytes = Vec::new();
|
||||
for id in ids {
|
||||
bytes.extend(decoder.push(*id)?);
|
||||
}
|
||||
bytes.extend(decoder.finish());
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Qwen3.5 decodes token by token with no state.
|
||||
struct QwenDecoder(Arc<leleka_tokenizer::Tokenizer>);
|
||||
|
||||
impl TokenDecoder for QwenDecoder {
|
||||
fn push(&mut self, id: u32) -> Result<Vec<u8>, String> {
|
||||
self.0.decode_bytes(&[id]).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn finish(&mut self) -> Vec<u8> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// The Qwen tokenizer as a codec; hold it in an `Arc` and call [`qwen_codec`].
|
||||
pub struct QwenCodec(Arc<leleka_tokenizer::Tokenizer>);
|
||||
|
||||
@@ -105,7 +74,7 @@ pub fn qwen_codec_shared(tokenizer: Arc<leleka_tokenizer::Tokenizer>) -> QwenCod
|
||||
}
|
||||
|
||||
impl QwenCodec {
|
||||
/// The text of `ids` (tests and tools; the Responses code decodes through [`TextCodec::decoder`]).
|
||||
/// The text of `ids` (tests and tools; the Responses code reads output through the decoders of the codec).
|
||||
pub fn decode(&self, ids: &[u32]) -> Result<String, String> {
|
||||
self.0.decode(ids).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -122,12 +91,12 @@ impl TextCodec for QwenCodec {
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn decoder(&self) -> Box<dyn TokenDecoder> {
|
||||
Box::new(QwenDecoder(self.0.clone()))
|
||||
fn live_decoder<'a>(&self, plan: LivePlan<'a>) -> Option<LiveDecoder<'a>> {
|
||||
Some(LiveDecoder::qwen(self.0.clone(), plan))
|
||||
}
|
||||
|
||||
fn output_decoder<'a>(&self, plan: ReadPlan<'a>) -> OutputDecoder<'a> {
|
||||
OutputDecoder::qwen(self.0.clone(), plan)
|
||||
fn at_end_decoder(&self, plan: AtEndPlan) -> AtEndDecoder {
|
||||
AtEndDecoder::qwen(self.0.clone(), plan)
|
||||
}
|
||||
|
||||
/// Control-token text inside the messages is marked by the renderer and encoded as ordinary text
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! * `sampling`: the sampling extensions a client may send and their validation, `EngineTune`.
|
||||
//! * `reasoning_budget`: the thinking budget driver (generic over the engine and the tokenizer).
|
||||
//! * `codec`: the model family (`TextCodec`, `Family`, `TokenDecoder`) as the Responses code sees it.
|
||||
//! * `codec`: the model family (`TextCodec`, `Family`) as the Responses code sees it.
|
||||
//! * `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.
|
||||
@@ -19,6 +19,8 @@ pub mod messages;
|
||||
pub mod output;
|
||||
pub mod reasoning_budget;
|
||||
pub mod responses;
|
||||
pub mod sampler_limit;
|
||||
pub mod sampling;
|
||||
mod think_marker;
|
||||
|
||||
pub use sampling::EngineTune;
|
||||
|
||||
@@ -2,30 +2,34 @@
|
||||
//!
|
||||
//! 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.
|
||||
//! never asks which family produced them. A family is an adapter behind the bytes of the decoders; the dispatch is an
|
||||
//! enum, so nothing is a trait object per token.
|
||||
//!
|
||||
//! Two readings exist because the gateway publishes in two ways:
|
||||
//! Two readings exist because the gateway publishes in two ways, and each has a decoder of its own type, so what one
|
||||
//! offers cannot be asked of the other:
|
||||
//!
|
||||
//! * [`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.
|
||||
//! * [`LiveDecoder`] (plan [`LivePlan`]): text and tool calls are published as they complete (no reasoning, no
|
||||
//! structured output). Every event of `push` and `finish` is final.
|
||||
//! * [`AtEndDecoder`] (plan [`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 cut;
|
||||
mod event;
|
||||
mod fold;
|
||||
mod harmony;
|
||||
mod live;
|
||||
mod reasoning_split;
|
||||
mod reasoning_preview;
|
||||
mod token_bytes;
|
||||
mod utf8;
|
||||
|
||||
pub use decoder::{AtEndPlan, LivePlan, OutputDecoder, ReadPlan};
|
||||
pub use event::{OutputError, OutputEvent};
|
||||
pub use at_end::{AtEndDecoder, AtEndPlan};
|
||||
pub use cut::cut_reasoning_for_corpus;
|
||||
pub use event::{GENERATION_ENDED, OutputError, OutputEvent};
|
||||
pub use fold::output_items;
|
||||
pub use harmony::HarmonyDecoder;
|
||||
pub use utf8::drain_utf8;
|
||||
pub use live::{LiveDecoder, LivePlan};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
//! The reading at the end: the answer is read once the generation is over (reasoning, structured output).
|
||||
|
||||
use super::cut::{CallScan, CutGeneration, Generation, cut_text};
|
||||
use super::event::{OutputError, OutputEvent};
|
||||
use super::reasoning_split::ReasoningSplit;
|
||||
use super::harmony::HarmonyDecoder;
|
||||
use super::reasoning_preview::ReasoningPreview;
|
||||
use super::token_bytes::{TokenBytes, ensure_open};
|
||||
use leleka_gateway_text::tool_output::{self, Notes, Options};
|
||||
use leleka_worker_protocol::Finish;
|
||||
use serde_json::Value;
|
||||
|
||||
const THINK_END: &[u8] = b"</think>";
|
||||
use std::sync::Arc;
|
||||
|
||||
/// What a reading at the end needs.
|
||||
pub struct AtEndPlan {
|
||||
/// The output starts inside a reasoning block that ends with `</think>`.
|
||||
pub reasoning: bool,
|
||||
/// Show the reasoning as it arrives (`push` returns `ReasoningDelta` events); off when nobody watches.
|
||||
pub preview: 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.
|
||||
@@ -20,202 +24,198 @@ pub struct AtEndPlan {
|
||||
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 {
|
||||
/// The decoder of one generation read at its end: `push` returns only reasoning previews; `finish` returns the events
|
||||
/// that make up the response.
|
||||
pub struct AtEndDecoder {
|
||||
bytes: TokenBytes,
|
||||
plan: AtEndPlan,
|
||||
bytes: Vec<u8>,
|
||||
heard: Vec<u8>,
|
||||
/// With reasoning: the bytes the generation had produced after each token.
|
||||
ends: Vec<usize>,
|
||||
tokens: u64,
|
||||
preview: ReasoningSplit,
|
||||
preview: ReasoningPreview,
|
||||
notes: Notes,
|
||||
call_in_reasoning: bool,
|
||||
copy: Option<(Option<String>, String)>,
|
||||
split_copy: Option<(Option<String>, String)>,
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
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> {
|
||||
fn wrap_reasoning_delta(text: String) -> Vec<OutputEvent> {
|
||||
if text.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![OutputEvent::ReasoningDelta(text)]
|
||||
}
|
||||
}
|
||||
|
||||
/// An answer has at least one text event, empty if there is nothing else.
|
||||
fn ensure_text(events: &mut Vec<OutputEvent>) {
|
||||
if events.is_empty() {
|
||||
events.push(OutputEvent::Text(String::new()));
|
||||
}
|
||||
}
|
||||
|
||||
impl AtEndDecoder {
|
||||
/// The decoder of a Qwen3.5 generation.
|
||||
pub fn qwen(tokenizer: Arc<leleka_tokenizer::Tokenizer>, plan: AtEndPlan) -> Self {
|
||||
Self::new(TokenBytes::Qwen(tokenizer), plan)
|
||||
}
|
||||
|
||||
/// The decoder of a gpt-oss generation.
|
||||
pub fn harmony(decoder: HarmonyDecoder, plan: AtEndPlan) -> Self {
|
||||
Self::new(TokenBytes::Harmony(decoder), plan)
|
||||
}
|
||||
|
||||
/// A decoder whose id `n` is byte `n` of `script`.
|
||||
#[cfg(test)]
|
||||
pub(super) fn scripted(script: &str, plan: AtEndPlan) -> Self {
|
||||
Self::new(TokenBytes::script(script), plan)
|
||||
}
|
||||
|
||||
/// A decoder whose id `n` is the bytes of `tokens[n]`.
|
||||
#[cfg(test)]
|
||||
pub(super) fn scripted_tokens(tokens: &[&str], plan: AtEndPlan) -> Self {
|
||||
let tokens = tokens.iter().map(|token| token.as_bytes().to_vec());
|
||||
Self::new(TokenBytes::Script(tokens.collect()), plan)
|
||||
}
|
||||
|
||||
fn new(bytes: TokenBytes, plan: AtEndPlan) -> Self {
|
||||
Self {
|
||||
bytes,
|
||||
plan,
|
||||
heard: Vec::new(),
|
||||
ends: Vec::new(),
|
||||
tokens: 0,
|
||||
preview: ReasoningPreview::default(),
|
||||
notes: Notes::default(),
|
||||
call_in_reasoning: false,
|
||||
split_copy: None,
|
||||
ended: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep one more generated token; the reasoning text it completes is returned for display.
|
||||
pub fn push(&mut self, id: u32) -> Result<Vec<OutputEvent>, OutputError> {
|
||||
ensure_open(self.ended)?;
|
||||
let bytes = self.bytes.push(id)?;
|
||||
self.tokens += 1;
|
||||
self.heard.extend_from_slice(&bytes);
|
||||
if !self.plan.reasoning {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
self.ends.push(self.heard.len());
|
||||
if !self.plan.preview {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(wrap_reasoning_delta(self.preview.push(&bytes)))
|
||||
}
|
||||
|
||||
/// The generation ended with `finish`: the events that make up the response.
|
||||
pub fn finish(&mut self, finish: Finish) -> Result<Vec<OutputEvent>, OutputError> {
|
||||
ensure_open(self.ended)?;
|
||||
self.ended = true;
|
||||
let mut events = self.flush_preview(finish);
|
||||
let tail = self.bytes.drain_tail();
|
||||
self.heard.extend_from_slice(&tail);
|
||||
let (cut, tokens) = self.cut_generation(finish)?;
|
||||
self.keep_split_copy(&cut);
|
||||
self.call_in_reasoning = cut.call_in_reasoning;
|
||||
events.extend(self.build_events(cut, tokens, finish)?);
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
/// The reasoning text still held back, shown when the generation was cut at the length limit.
|
||||
fn flush_preview(&mut self, finish: Finish) -> Vec<OutputEvent> {
|
||||
if self.plan.reasoning && self.plan.preview && finish == Finish::Length {
|
||||
return wrap_reasoning_delta(self.preview.finish());
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The generation cut in two and the tokens its reasoning took.
|
||||
fn cut_generation(&self, finish: Finish) -> Result<(CutGeneration, u64), OutputError> {
|
||||
let scan = CallScan {
|
||||
tools: self.plan.tools.as_deref(),
|
||||
recovery: self.plan.recovery,
|
||||
};
|
||||
let cut = cut_text(&self.heard, self.plan.reasoning, finish, &scan)?;
|
||||
let generation = Generation {
|
||||
ends: &self.ends,
|
||||
tokens: self.tokens,
|
||||
};
|
||||
let tokens = generation.count_tokens(&cut.extent);
|
||||
Ok((cut, tokens))
|
||||
}
|
||||
|
||||
fn keep_split_copy(&mut self, cut: &CutGeneration) {
|
||||
if self.plan.keep_raw {
|
||||
let reasoning = cut.reasoning.as_ref().map(|(text, _)| text.clone());
|
||||
self.split_copy = Some((reasoning, cut.answer.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The reasoning event, then the answer events unless the reasoning was cut.
|
||||
fn build_events(
|
||||
&mut self,
|
||||
cut: CutGeneration,
|
||||
tokens: u64,
|
||||
finish: Finish,
|
||||
) -> Result<Vec<OutputEvent>, OutputError> {
|
||||
let mut events = Vec::new();
|
||||
let mut cut_short = false;
|
||||
if let Some((text, complete)) = cut.reasoning {
|
||||
cut_short = !complete;
|
||||
events.push(OutputEvent::Reasoned {
|
||||
text,
|
||||
complete,
|
||||
tokens,
|
||||
});
|
||||
}
|
||||
if !cut_short {
|
||||
let (answer, notes) = self.read_answer(&cut.answer, finish)?;
|
||||
self.notes = notes;
|
||||
events.extend(answer);
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
/// The answer as text and whole calls, and what was accepted beyond the template form; a call that is not
|
||||
/// acceptable is a parse error.
|
||||
fn read_answer(
|
||||
&self,
|
||||
answer: &str,
|
||||
finish: Finish,
|
||||
) -> Result<(Vec<OutputEvent>, Notes), OutputError> {
|
||||
let (mut events, notes) = match self.plan.tools.as_deref() {
|
||||
None => (vec![OutputEvent::Text(answer.to_owned())], Notes::default()),
|
||||
Some(tools) => {
|
||||
let options = Options {
|
||||
natural_stop: finish != Finish::Length,
|
||||
recovery: self.plan.recovery,
|
||||
};
|
||||
let parsed =
|
||||
tool_output::parse_with(answer, tools, options).map_err(OutputError::Parse)?;
|
||||
let events = parsed.segments.into_iter().map(OutputEvent::from);
|
||||
(events.collect(), parsed.notes)
|
||||
}
|
||||
};
|
||||
ensure_text(&mut events);
|
||||
Ok((events, notes))
|
||||
}
|
||||
|
||||
/// What was accepted although the template form of a tool call was not followed.
|
||||
pub fn notes(&self) -> &Notes {
|
||||
&self.notes
|
||||
}
|
||||
|
||||
/// Calls were accepted although the reasoning never closed.
|
||||
pub fn accepted_call_in_reasoning(&self) -> bool {
|
||||
self.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)> {
|
||||
let (reasoning, answer) = self.split_copy.as_ref()?;
|
||||
Some((reasoning.as_deref(), answer))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Cutting a finished generation into its reasoning and its answer, and counting the tokens the reasoning took.
|
||||
|
||||
use super::event::OutputError;
|
||||
use crate::think_marker;
|
||||
use leleka_gateway_text::tool_output::{self, Options};
|
||||
use leleka_worker_protocol::Finish;
|
||||
use serde_json::Value;
|
||||
|
||||
/// What is known of the tokens of a finished generation.
|
||||
pub(super) struct Generation<'a> {
|
||||
/// With reasoning: the bytes the generation had produced after each token.
|
||||
pub ends: &'a [usize],
|
||||
pub tokens: u64,
|
||||
}
|
||||
|
||||
/// How a call at the end of unclosed reasoning is recognised.
|
||||
pub(super) struct CallScan<'a> {
|
||||
pub tools: Option<&'a [Value]>,
|
||||
pub recovery: bool,
|
||||
}
|
||||
|
||||
/// Which tokens of the generation the reasoning took, as a place in its bytes.
|
||||
pub(super) enum Extent {
|
||||
/// There is no reasoning.
|
||||
Nothing,
|
||||
/// The tokens up to the one that brought the text to this many bytes.
|
||||
Through(usize),
|
||||
/// The tokens whose text lies before this byte.
|
||||
Before(usize),
|
||||
/// All of them.
|
||||
All,
|
||||
}
|
||||
|
||||
/// The generation cut into its reasoning and its answer; the tokens the reasoning took are counted from `extent`.
|
||||
pub(super) struct CutGeneration {
|
||||
/// The reasoning text and whether the model closed it; `None` when the output did not start in reasoning.
|
||||
pub reasoning: Option<(String, bool)>,
|
||||
pub answer: String,
|
||||
pub extent: Extent,
|
||||
/// The text ended on whole calls of declared tools although the reasoning never closed.
|
||||
pub call_in_reasoning: bool,
|
||||
}
|
||||
|
||||
/// The text of bytes that may be cut inside a character: an invalid run becomes one U+FFFD.
|
||||
pub(super) fn decode_lossy(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
|
||||
/// The reasoning and the answer of the text of a generation that started inside a reasoning block, as the readers cut
|
||||
/// them; `finish` is how it ended and `tools` the declarations a call at the end of unclosed reasoning is checked
|
||||
/// against. The tool corpus tests use this, so they cut as the gateway does.
|
||||
pub fn cut_reasoning_for_corpus(
|
||||
text: &str,
|
||||
finish: Finish,
|
||||
tools: &[Value],
|
||||
recovery: bool,
|
||||
) -> Result<(String, String), String> {
|
||||
let scan = CallScan {
|
||||
tools: Some(tools),
|
||||
recovery,
|
||||
};
|
||||
let cut = cut_text(text.as_bytes(), true, finish, &scan).map_err(|error| error.to_string())?;
|
||||
let reasoning = cut.reasoning.map(|(text, _)| text).unwrap_or_default();
|
||||
Ok((reasoning, cut.answer))
|
||||
}
|
||||
|
||||
/// Cut the bytes; `reasoning`: the output started inside a reasoning block.
|
||||
pub(super) fn cut_text(
|
||||
bytes: &[u8],
|
||||
reasoning: bool,
|
||||
finish: Finish,
|
||||
scan: &CallScan<'_>,
|
||||
) -> Result<CutGeneration, OutputError> {
|
||||
if !reasoning {
|
||||
return Ok(CutGeneration {
|
||||
reasoning: None,
|
||||
answer: decode_lossy(bytes),
|
||||
extent: Extent::Nothing,
|
||||
call_in_reasoning: false,
|
||||
});
|
||||
}
|
||||
match think_marker::find_end(bytes) {
|
||||
Some(at) => Ok(cut_closed(bytes, at)),
|
||||
None => cut_unclosed(bytes, finish, scan),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text has a `</think>` at byte `at`: the reasoning before it, the answer after it.
|
||||
fn cut_closed(bytes: &[u8], at: usize) -> CutGeneration {
|
||||
let end = at + think_marker::THINK_END.len();
|
||||
CutGeneration {
|
||||
reasoning: Some((decode_lossy(&bytes[..at]), true)),
|
||||
answer: decode_lossy(&bytes[end..])
|
||||
.trim_start_matches('\n')
|
||||
.to_owned(),
|
||||
extent: Extent::Through(end),
|
||||
call_in_reasoning: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The generation ended at the length limit inside its reasoning: all of it is reasoning, and it is not complete.
|
||||
fn cut_short(text: String) -> CutGeneration {
|
||||
CutGeneration {
|
||||
reasoning: Some((text, false)),
|
||||
answer: String::new(),
|
||||
extent: Extent::All,
|
||||
call_in_reasoning: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The text has no `</think>`: at the length limit the reasoning is cut; after a natural stop the text must end on
|
||||
/// whole calls of declared tools, which are then the answer (the reasoning item ends before them).
|
||||
fn cut_unclosed(
|
||||
bytes: &[u8],
|
||||
finish: Finish,
|
||||
scan: &CallScan<'_>,
|
||||
) -> Result<CutGeneration, OutputError> {
|
||||
let text = decode_lossy(bytes);
|
||||
if finish == Finish::Length {
|
||||
return Ok(cut_short(text));
|
||||
}
|
||||
let options = Options {
|
||||
natural_stop: true,
|
||||
recovery: scan.recovery,
|
||||
};
|
||||
let tools = scan.tools.unwrap_or(&[]);
|
||||
let Some(at) = tool_output::calls_at_end(&text, tools, options) else {
|
||||
return Err(OutputError::Decode(
|
||||
"reasoning ended without </think>".into(),
|
||||
));
|
||||
};
|
||||
Ok(CutGeneration {
|
||||
reasoning: Some((text[..at].to_owned(), true)),
|
||||
answer: text[at..].to_owned(),
|
||||
extent: Extent::Before(at),
|
||||
call_in_reasoning: true,
|
||||
})
|
||||
}
|
||||
|
||||
impl Generation<'_> {
|
||||
/// The tokens the reasoning took.
|
||||
pub(super) fn count_tokens(&self, extent: &Extent) -> u64 {
|
||||
match extent {
|
||||
Extent::Nothing => 0,
|
||||
Extent::Through(end) => self.count_tokens_through(*end),
|
||||
Extent::Before(at) => self.count_tokens_before(*at),
|
||||
Extent::All => self.tokens,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tokens up to the one that brought the text to `end` bytes (all of them if none did).
|
||||
fn count_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 count_tokens_before(&self, at: usize) -> u64 {
|
||||
if at == 0 {
|
||||
return 0;
|
||||
}
|
||||
self.count_tokens_through(at)
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
//! 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,9 @@ impl From<Segment> for OutputEvent {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a decode error says when a generation is pushed to or finished after it ended.
|
||||
pub const GENERATION_ENDED: &str = "the generation has already ended";
|
||||
|
||||
/// Why the output could not be read. The class decides the error the client gets.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum OutputError {
|
||||
|
||||
@@ -16,13 +16,13 @@ pub fn output_items(events: Vec<OutputEvent>, response_id: &str) -> (Vec<OutputI
|
||||
.iter()
|
||||
.filter(|item| !matches!(item, OutputItem::Reasoning { .. }))
|
||||
.count();
|
||||
items.extend(item_of(event, response_id, answers));
|
||||
items.extend(build_item(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> {
|
||||
fn build_item(event: OutputEvent, response_id: &str, index: usize) -> Option<OutputItem> {
|
||||
match event {
|
||||
OutputEvent::ReasoningDelta(_) => None,
|
||||
OutputEvent::Reasoned { text, complete, .. } => Some(OutputItem::Reasoning {
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
//! `<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;
|
||||
@@ -155,8 +154,9 @@ fn tool_markup(name: &str, arguments: &str) -> Result<String, String> {
|
||||
Ok(markup)
|
||||
}
|
||||
|
||||
impl TokenDecoder for HarmonyDecoder {
|
||||
fn push(&mut self, id: u32) -> Result<Vec<u8>, String> {
|
||||
impl HarmonyDecoder {
|
||||
/// The markup bytes for one more generated token.
|
||||
pub 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(""));
|
||||
@@ -187,7 +187,7 @@ impl TokenDecoder for HarmonyDecoder {
|
||||
|
||||
/// 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> {
|
||||
pub fn finish(&mut self) -> Vec<u8> {
|
||||
let mut out = String::new();
|
||||
let pending = self.utf8.finish();
|
||||
if !pending.is_empty() {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! The live reading: text and whole tool calls as the bytes arrive.
|
||||
|
||||
use super::event::{OutputError, OutputEvent};
|
||||
use super::token_bytes::{TokenBytes, ensure_open};
|
||||
use super::utf8::drain_utf8;
|
||||
use leleka_gateway_text::tool_output::{Incremental, Notes, Options, Segment};
|
||||
use leleka_worker_protocol::Finish;
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// What a live reading needs: the declarations of the request's tools (`None`: no tools, everything is text).
|
||||
pub struct LivePlan<'a> {
|
||||
@@ -15,36 +17,54 @@ pub struct LivePlan<'a> {
|
||||
pub keep_raw: bool,
|
||||
}
|
||||
|
||||
pub(super) struct LiveReader<'a> {
|
||||
/// The decoder of one generation read live: every event of `push` and `finish` is final.
|
||||
pub struct LiveDecoder<'a> {
|
||||
bytes: TokenBytes,
|
||||
pending: Vec<u8>,
|
||||
parser: Option<Incremental<'a>>,
|
||||
raw: Option<String>,
|
||||
no_notes: Notes,
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
fn events(segments: Vec<Segment>) -> Vec<OutputEvent> {
|
||||
fn convert_segments(segments: Vec<Segment>) -> Vec<OutputEvent> {
|
||||
segments.into_iter().map(OutputEvent::from).collect()
|
||||
}
|
||||
|
||||
impl<'a> LiveReader<'a> {
|
||||
pub(super) fn new(plan: LivePlan<'a>) -> Self {
|
||||
impl<'a> LiveDecoder<'a> {
|
||||
/// The decoder of a Qwen3.5 generation.
|
||||
pub fn qwen(tokenizer: Arc<leleka_tokenizer::Tokenizer>, plan: LivePlan<'a>) -> Self {
|
||||
Self::new(TokenBytes::Qwen(tokenizer), plan)
|
||||
}
|
||||
|
||||
/// A decoder whose id `n` is byte `n` of `script`.
|
||||
#[cfg(test)]
|
||||
pub(super) fn scripted(script: &str, plan: LivePlan<'a>) -> Self {
|
||||
Self::new(TokenBytes::script(script), plan)
|
||||
}
|
||||
|
||||
fn new(bytes: TokenBytes, plan: LivePlan<'a>) -> Self {
|
||||
let options = Options {
|
||||
natural_stop: false,
|
||||
recovery: plan.recovery,
|
||||
};
|
||||
Self {
|
||||
bytes,
|
||||
pending: Vec::new(),
|
||||
parser: plan
|
||||
.tools
|
||||
.map(|tools| Incremental::with_options(tools, options)),
|
||||
raw: plan.keep_raw.then(String::new),
|
||||
no_notes: Notes::default(),
|
||||
ended: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
/// The events one more generated token completes.
|
||||
pub fn push(&mut self, id: u32) -> Result<Vec<OutputEvent>, OutputError> {
|
||||
ensure_open(self.ended)?;
|
||||
let bytes = self.bytes.push(id)?;
|
||||
self.pending.extend_from_slice(&bytes);
|
||||
let delta = drain_utf8(&mut self.pending, false);
|
||||
if delta.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -55,11 +75,18 @@ impl<'a> LiveReader<'a> {
|
||||
let Some(parser) = self.parser.as_mut() else {
|
||||
return Ok(vec![OutputEvent::Text(delta)]);
|
||||
};
|
||||
parser.feed(&delta).map(events).map_err(OutputError::Parse)
|
||||
parser
|
||||
.feed(&delta)
|
||||
.map(convert_segments)
|
||||
.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> {
|
||||
/// The generation ended with `finish`: the text and calls that are left.
|
||||
pub fn finish(&mut self, finish: Finish) -> Result<Vec<OutputEvent>, OutputError> {
|
||||
ensure_open(self.ended)?;
|
||||
self.ended = true;
|
||||
let tail = self.bytes.drain_tail();
|
||||
self.pending.extend_from_slice(&tail);
|
||||
let rest = drain_utf8(&mut self.pending, true);
|
||||
let Some(parser) = self.parser.as_mut() else {
|
||||
return Ok(if rest.is_empty() {
|
||||
@@ -71,16 +98,18 @@ impl<'a> LiveReader<'a> {
|
||||
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))
|
||||
Ok(convert_segments(segments))
|
||||
}
|
||||
|
||||
pub(super) fn notes(&self) -> &Notes {
|
||||
/// What was accepted although the template form of a tool call was not followed.
|
||||
pub fn notes(&self) -> &Notes {
|
||||
self.parser
|
||||
.as_ref()
|
||||
.map_or(&self.no_notes, Incremental::notes)
|
||||
}
|
||||
|
||||
pub(super) fn raw(&self) -> Option<&str> {
|
||||
/// The text read so far, when the plan kept it.
|
||||
pub fn raw_text(&self) -> Option<&str> {
|
||||
self.raw.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
+6
-14
@@ -1,28 +1,23 @@
|
||||
//! The reasoning text of a stream that ends with `</think>`, cut out of the byte pieces as they arrive.
|
||||
|
||||
use super::utf8::drain_utf8;
|
||||
use crate::think_marker;
|
||||
|
||||
const MARKER: &[u8] = b"</think>";
|
||||
|
||||
/// Splits the reasoning off a byte stream: the text before `</think>`, which may arrive across pieces.
|
||||
/// Shows the reasoning of a byte stream as it arrives: the text before `</think>`, which may come across pieces.
|
||||
#[derive(Default)]
|
||||
pub(super) struct ReasoningSplit {
|
||||
pub(super) struct ReasoningPreview {
|
||||
pending: Vec<u8>,
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
impl ReasoningSplit {
|
||||
impl ReasoningPreview {
|
||||
/// 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)
|
||||
{
|
||||
if let Some(at) = think_marker::find_end(&self.pending) {
|
||||
let text = String::from_utf8_lossy(&self.pending[..at]).into_owned();
|
||||
self.pending.clear();
|
||||
self.ended = true;
|
||||
@@ -33,10 +28,7 @@ impl ReasoningSplit {
|
||||
|
||||
/// 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 keep = think_marker::held_prefix_len(&self.pending);
|
||||
let tail = self.pending.split_off(self.pending.len() - keep);
|
||||
let text = drain_utf8(&mut self.pending, false);
|
||||
self.pending.extend_from_slice(&tail);
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Unit tests of the output decoder over a decoder that maps each id to fixed bytes.
|
||||
//! Unit tests of the output decoders over a decoder that maps each id to fixed bytes.
|
||||
|
||||
use super::utf8::drain_utf8;
|
||||
use super::*;
|
||||
use leleka_worker_protocol::Finish;
|
||||
use serde_json::{Value, json};
|
||||
@@ -12,44 +13,59 @@ fn lookup() -> Vec<Value> {
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
fn live_plan(tools: Option<&[Value]>, keep_raw: bool) -> LivePlan<'_> {
|
||||
LivePlan {
|
||||
tools,
|
||||
recovery: false,
|
||||
keep_raw,
|
||||
}
|
||||
}
|
||||
|
||||
fn at_end_plan(reasoning: bool, tools: Option<Vec<Value>>) -> AtEndPlan {
|
||||
AtEndPlan {
|
||||
reasoning,
|
||||
preview: true,
|
||||
tools,
|
||||
recovery: false,
|
||||
keep_raw: false,
|
||||
}
|
||||
}
|
||||
|
||||
type Run = (Vec<OutputEvent>, Result<Vec<OutputEvent>, OutputError>);
|
||||
|
||||
/// The events of each push of a live reading, then those of its finish.
|
||||
fn run_live(script: &str, plan: LivePlan<'_>, finish: Finish) -> Run {
|
||||
let mut decoder = LiveDecoder::scripted(script, plan);
|
||||
let pushed = (0..script.len() as u32)
|
||||
.flat_map(|id| decoder.push(id).unwrap())
|
||||
.collect();
|
||||
(pushed, decoder.finish(finish))
|
||||
}
|
||||
|
||||
/// The same for a reading at the end.
|
||||
fn run_at_end(script: &str, plan: AtEndPlan, finish: Finish) -> Run {
|
||||
let mut decoder = AtEndDecoder::scripted(script, plan);
|
||||
let pushed = (0..script.len() as u32)
|
||||
.flat_map(|id| decoder.push(id).unwrap())
|
||||
.collect();
|
||||
(pushed, decoder.finish(finish))
|
||||
}
|
||||
|
||||
fn reasoned(value: &str, complete: bool, tokens: u64) -> OutputEvent {
|
||||
OutputEvent::Reasoned {
|
||||
text: value.to_owned(),
|
||||
complete,
|
||||
tokens,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_reading_without_tools_passes_the_text_on() {
|
||||
let (pushed, finished) = run("Hello", live(None), Finish::Stop);
|
||||
let (pushed, finished) = run_live("Hello", live_plan(None, false), Finish::Stop);
|
||||
assert_eq!(pushed, ["H", "e", "l", "l", "o"].map(text));
|
||||
assert_eq!(finished.unwrap(), vec![]);
|
||||
}
|
||||
@@ -58,7 +74,7 @@ fn a_live_reading_without_tools_passes_the_text_on() {
|
||||
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 (pushed, finished) = run_live(&script, live_plan(Some(&tools), false), Finish::Stop);
|
||||
let events: Vec<_> = pushed.into_iter().chain(finished.unwrap()).collect();
|
||||
let call = OutputEvent::Call {
|
||||
name: "lookup".into(),
|
||||
@@ -76,77 +92,131 @@ fn a_live_reading_with_tools_publishes_a_call_when_it_is_whole() {
|
||||
}
|
||||
|
||||
#[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);
|
||||
fn a_live_reading_keeps_the_text_for_the_debug_copy_only_when_asked() {
|
||||
let mut kept = LiveDecoder::scripted("abc", live_plan(None, true));
|
||||
let mut dropped = LiveDecoder::scripted("abc", live_plan(None, false));
|
||||
for id in 0..3 {
|
||||
kept.push(id).unwrap();
|
||||
dropped.push(id).unwrap();
|
||||
}
|
||||
assert_eq!(kept.raw_text(), Some("abc"));
|
||||
assert_eq!(dropped.raw_text(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_reading_ends_a_character_that_stays_cut_as_a_replacement() {
|
||||
let mut decoder = LiveDecoder::scripted("", live_plan(None, false));
|
||||
assert_eq!(
|
||||
pushed,
|
||||
["t", "h", "i", "n", "k"].map(|piece| OutputEvent::ReasoningDelta(piece.into()))
|
||||
decoder.push(0),
|
||||
Err(OutputError::Decode("no token 0".into()))
|
||||
);
|
||||
let reasoned = OutputEvent::Reasoned {
|
||||
text: "think".into(),
|
||||
complete: true,
|
||||
tokens: 13,
|
||||
let mut cut = LiveDecoder::scripted("\u{20ac}", live_plan(None, false));
|
||||
assert_eq!(cut.push(0).unwrap(), vec![]);
|
||||
assert_eq!(cut.finish(Finish::Length).unwrap(), vec![text("\u{fffd}")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_is_previewed_and_returned_whole_at_the_end() {
|
||||
let script = "think</think>\n\nanswer";
|
||||
let (pushed, finished) = run_at_end(script, at_end_plan(true, None), Finish::Stop);
|
||||
let pieces = ["t", "h", "i", "n", "k"].map(|piece| OutputEvent::ReasoningDelta(piece.into()));
|
||||
assert_eq!(pushed, pieces);
|
||||
assert_eq!(
|
||||
finished.unwrap(),
|
||||
vec![reasoned("think", true, 13), text("answer")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_previewed_when_the_plan_says_nobody_watches() {
|
||||
let plan = AtEndPlan {
|
||||
preview: false,
|
||||
..at_end_plan(true, None)
|
||||
};
|
||||
assert_eq!(finished.unwrap(), vec![reasoned, text("answer")]);
|
||||
let (pushed, finished) = run_at_end("think</think>\n\nanswer", plan, Finish::Stop);
|
||||
assert_eq!(pushed, vec![]);
|
||||
assert_eq!(
|
||||
finished.unwrap(),
|
||||
vec![reasoned("think", true, 13), 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()
|
||||
))
|
||||
);
|
||||
let (_, finished) = run_at_end("still", at_end_plan(true, None), Finish::Length);
|
||||
assert_eq!(finished.unwrap(), vec![reasoned("still", false, 5)]);
|
||||
let (_, finished) = run_at_end("still", at_end_plan(true, None), Finish::Stop);
|
||||
let message = "reasoning ended without </think>".to_owned();
|
||||
assert_eq!(finished, Err(OutputError::Decode(message)));
|
||||
}
|
||||
|
||||
#[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")
|
||||
);
|
||||
let mut decoder = AtEndDecoder::scripted(&script, at_end_plan(true, Some(lookup())));
|
||||
for id in 0..script.len() as u32 {
|
||||
decoder.push(id).unwrap();
|
||||
}
|
||||
let events = decoder.finish(Finish::Stop).unwrap();
|
||||
assert_eq!(events[0], reasoned("I will look.\n", true, 13));
|
||||
assert!(matches!(&events[1], OutputEvent::Call { name, .. } if name == "lookup"));
|
||||
assert!(decoder.accepted_call_in_reasoning());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_without_calls_is_one_text_event_even_when_empty() {
|
||||
let (_, finished) = run("", at_end(false, None), Finish::Stop);
|
||||
let (_, finished) = run_at_end("", at_end_plan(false, None), Finish::Stop);
|
||||
assert_eq!(finished.unwrap(), vec![text("")]);
|
||||
let (_, finished) = run("", at_end(false, Some(lookup())), Finish::Stop);
|
||||
let (_, finished) = run_at_end("", at_end_plan(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);
|
||||
let (_, finished) = run_at_end(script, at_end_plan(false, Some(lookup())), Finish::Stop);
|
||||
assert!(matches!(finished, Err(OutputError::Parse(_))));
|
||||
let mut decoder = OutputDecoder::scripted("", at_end(false, None));
|
||||
let mut decoder = AtEndDecoder::scripted("", at_end_plan(false, None));
|
||||
assert_eq!(
|
||||
decoder.push(0),
|
||||
Err(OutputError::Decode("no token 0".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_debug_copy_of_a_refused_answer_is_kept_only_when_asked() {
|
||||
let answer = "<tool_call><function=nope></function></tool_call>";
|
||||
let script = format!("r</think>\n\n{answer}");
|
||||
for (keep_raw, expected) in [(true, Some((Some("r"), answer))), (false, None)] {
|
||||
let plan = AtEndPlan {
|
||||
keep_raw,
|
||||
..at_end_plan(true, Some(lookup()))
|
||||
};
|
||||
let mut decoder = AtEndDecoder::scripted(&script, plan);
|
||||
for id in 0..script.len() as u32 {
|
||||
decoder.push(id).unwrap();
|
||||
}
|
||||
assert!(decoder.finish(Finish::Stop).is_err());
|
||||
assert_eq!(decoder.split_text(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generation_ends_once() {
|
||||
let mut live = LiveDecoder::scripted("ab", live_plan(None, false));
|
||||
live.finish(Finish::Stop).unwrap();
|
||||
assert!(live.finish(Finish::Stop).is_err());
|
||||
assert!(live.push(0).is_err());
|
||||
let mut at_end = AtEndDecoder::scripted("ab", at_end_plan(false, None));
|
||||
at_end.finish(Finish::Stop).unwrap();
|
||||
assert!(at_end.finish(Finish::Stop).is_err());
|
||||
assert!(at_end.push(0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_number_calls_by_their_place_in_the_answer() {
|
||||
let events = vec![
|
||||
OutputEvent::Reasoned {
|
||||
text: "r".into(),
|
||||
complete: true,
|
||||
tokens: 3,
|
||||
},
|
||||
reasoned("r", true, 3),
|
||||
text("a"),
|
||||
OutputEvent::Call {
|
||||
name: "f".into(),
|
||||
@@ -164,7 +234,7 @@ fn items_number_calls_by_their_place_in_the_answer() {
|
||||
fn the_reasoning_marker_and_characters_may_split_anywhere() {
|
||||
let input = "Коротка думка</think>\n\n4".as_bytes();
|
||||
for split in 0..=input.len() {
|
||||
let mut stream = super::reasoning_split::ReasoningSplit::default();
|
||||
let mut stream = super::reasoning_preview::ReasoningPreview::default();
|
||||
let shown = stream.push(&input[..split]) + &stream.push(&input[split..]);
|
||||
assert_eq!(shown, "Коротка думка", "split at {split}");
|
||||
assert!(stream.finish().is_empty());
|
||||
@@ -180,3 +250,43 @@ fn utf8_waits_for_a_whole_character_and_replaces_what_stays_cut() {
|
||||
pending.extend_from_slice(&[0xf0, 0x9f]);
|
||||
assert_eq!(drain_utf8(&mut pending, true), "\u{fffd}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobody_watching_still_counts_the_tokens_and_cuts_a_reasoning_at_the_length_limit() {
|
||||
let plan = || AtEndPlan {
|
||||
preview: false,
|
||||
..at_end_plan(true, None)
|
||||
};
|
||||
let (pushed, finished) = run_at_end("a long thought", plan(), Finish::Length);
|
||||
assert_eq!(pushed, vec![]);
|
||||
assert_eq!(
|
||||
finished.unwrap(),
|
||||
vec![reasoned("a long thought", false, 14)]
|
||||
);
|
||||
}
|
||||
|
||||
/// The ids of a script whose tokens hold several bytes each: the marker is split over two of them.
|
||||
fn tokens_of_a_split_marker() -> [&'static str; 4] {
|
||||
["r\u{e9}", "x</thi", "nk>y", "\n\nok"]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reasoning_tokens_do_not_depend_on_who_watches() {
|
||||
let counts: Vec<_> = [true, false]
|
||||
.into_iter()
|
||||
.map(|preview| {
|
||||
let plan = AtEndPlan {
|
||||
preview,
|
||||
..at_end_plan(true, None)
|
||||
};
|
||||
let mut decoder = AtEndDecoder::scripted_tokens(&tokens_of_a_split_marker(), plan);
|
||||
for id in 0..4 {
|
||||
decoder.push(id).unwrap();
|
||||
}
|
||||
decoder.finish(Finish::Stop).unwrap()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(counts[0], counts[1]);
|
||||
assert_eq!(counts[0][0], reasoned("r\u{e9}x", true, 3));
|
||||
assert_eq!(counts[0][1], text("y\n\nok"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
//! The bytes a family's generated tokens stand for, shared by both readings.
|
||||
|
||||
use super::event::{GENERATION_ENDED, OutputError};
|
||||
use super::harmony::HarmonyDecoder;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) enum TokenBytes {
|
||||
/// 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 string per id, for the tests of the readers.
|
||||
#[cfg(test)]
|
||||
Script(Vec<Vec<u8>>),
|
||||
}
|
||||
|
||||
impl TokenBytes {
|
||||
/// A script whose id `n` is byte `n` of `text`.
|
||||
#[cfg(test)]
|
||||
pub(super) fn script(text: &str) -> Self {
|
||||
Self::Script(text.bytes().map(|byte| vec![byte]).collect())
|
||||
}
|
||||
|
||||
pub(super) 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(tokens) => tokens
|
||||
.get(id as usize)
|
||||
.cloned()
|
||||
.ok_or_else(|| OutputError::Decode(format!("no token {id}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes the decoder held back when the generation ended.
|
||||
pub(super) fn drain_tail(&mut self) -> Vec<u8> {
|
||||
match self {
|
||||
Self::Qwen(_) => Vec::new(),
|
||||
Self::Harmony(decoder) => decoder.finish(),
|
||||
#[cfg(test)]
|
||||
Self::Script(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generation ends once: nothing may be pushed or finished after that.
|
||||
pub(super) fn ensure_open(ended: bool) -> Result<(), OutputError> {
|
||||
if ended {
|
||||
return Err(OutputError::Decode(GENERATION_ENDED.into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
/// 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 {
|
||||
pub(super) 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) {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! wrap-up, the continuation prompt, the room check) is testable without a model; `tests/reasoning_budget_oracle.rs`
|
||||
//! replays cases produced by the unmodified Python `Service.run`.
|
||||
|
||||
use crate::think_marker;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
@@ -13,7 +14,6 @@ use serde_json::Value;
|
||||
/// What closes the thinking when it reaches the budget (the model's own end-of-thinking tag follows the sentence).
|
||||
pub const REASONING_WRAP_UP: &str =
|
||||
"\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n";
|
||||
const THINK_END: &str = "</think>";
|
||||
|
||||
/// An incremental UTF-8 decoder with replacement (`codecs.getincrementaldecoder("utf-8")(errors="replace")`): complete
|
||||
/// characters come out, a character split across tokens is held until it is whole.
|
||||
|
||||
@@ -230,15 +230,12 @@ impl ReasoningScan {
|
||||
return;
|
||||
}
|
||||
self.held.push_str(delta);
|
||||
if self.held.contains(THINK_END) {
|
||||
if think_marker::find_end(self.held.as_bytes()).is_some() {
|
||||
self.held.clear();
|
||||
self.reasoning = false;
|
||||
return;
|
||||
}
|
||||
let keep = (1..THINK_END.len())
|
||||
.rev()
|
||||
.find(|&len| self.held.ends_with(&THINK_END[..len]))
|
||||
.unwrap_or(0);
|
||||
let keep = think_marker::held_prefix_len(self.held.as_bytes());
|
||||
let cut = self.held.len() - keep;
|
||||
self.held.drain(..cut);
|
||||
}
|
||||
|
||||
@@ -11,18 +11,18 @@ pub mod prompt_date;
|
||||
pub mod render;
|
||||
pub mod request;
|
||||
pub mod schema;
|
||||
pub mod tool_calls;
|
||||
pub mod tool_declarations;
|
||||
pub mod trace;
|
||||
mod trace_items;
|
||||
pub mod validate;
|
||||
|
||||
pub use effort::{is_structured, reasoning_effort, reasoning_enabled, unsupported_gptoss_sampling};
|
||||
pub use effort::{is_structured, reasoning_effort, reasoning_enabled};
|
||||
pub use harmony_render::{render_at, render_dated};
|
||||
pub use output::{OutputItem, Usage};
|
||||
pub use prompt_date::{PromptDate, civil_date};
|
||||
pub use render::render_request_with;
|
||||
pub use request::{CreateRequest, TextFormat, TextOptions};
|
||||
pub use schema::{reject_remote_refs, tool_schema_accepted};
|
||||
pub use tool_calls::{flat_tools, parse_output_items_with};
|
||||
pub use tool_declarations::flat_tools;
|
||||
pub use trace::{ResponseTrace, text_part};
|
||||
pub use validate::{validate_live_subset, validate_text_format};
|
||||
|
||||
@@ -61,25 +61,6 @@ pub fn reasoning_enabled<C: TextCodec + ?Sized>(request: &CreateRequest, codec:
|
||||
codec.always_reasons() || reasoning_effort(request).is_ok_and(|effort| effort != Effort::None)
|
||||
}
|
||||
|
||||
/// The first sampler the request sets that the gpt-oss worker's `GEN` line cannot carry.
|
||||
pub fn unsupported_gptoss_sampling(
|
||||
sampling: &leleka_sampler_ref::RequestSampling,
|
||||
) -> Option<&'static str> {
|
||||
if sampling.top_k.is_some() {
|
||||
Some("top_k")
|
||||
} else if sampling.min_p.is_some() {
|
||||
Some("min_p")
|
||||
} else if sampling.repetition_penalty.is_some_and(|v| v != 1.0) {
|
||||
Some("repetition_penalty")
|
||||
} else if sampling.frequency_penalty.is_some_and(|v| v != 0.0) {
|
||||
Some("frequency_penalty")
|
||||
} else if sampling.presence_penalty.is_some_and(|v| v != 0.0) {
|
||||
Some("presence_penalty")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_structured(request: &CreateRequest) -> bool {
|
||||
request
|
||||
.text
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
//! Reading the model's answer text back into Responses items: the text and the tool calls (with the experimental
|
||||
//! recovery of drifted forms, when the caller turns it on). The reasoning block and the decoding of generated ids
|
||||
//! are `crate::output`; this reads an answer that is already text, as the golden tests and the tool corpus do.
|
||||
|
||||
use crate::responses::output::OutputItem;
|
||||
use crate::responses::request::CreateRequest;
|
||||
use leleka_gateway_text::{
|
||||
response_tools::Catalog,
|
||||
tool_output::{self, Segment},
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
/// `options.natural_stop`: the generation ended by itself and not at the token limit, so a call that ends the text on
|
||||
/// `</function>` is whole. The notes say which calls were accepted beyond the template form; the caller logs them.
|
||||
pub fn parse_output_items_with(
|
||||
request: &CreateRequest,
|
||||
output: String,
|
||||
id: &str,
|
||||
options: tool_output::Options,
|
||||
) -> Result<(Vec<OutputItem>, tool_output::Notes), String> {
|
||||
if request.tools.is_empty() {
|
||||
let items = vec![OutputItem::Text {
|
||||
deltas: vec![output],
|
||||
}];
|
||||
return Ok((items, tool_output::Notes::default()));
|
||||
}
|
||||
let catalog = Catalog::new(&request.tools)?;
|
||||
let parsed = tool_output::parse_with(&output, &catalog.flat, options)?;
|
||||
let notes = parsed.notes;
|
||||
let mut items = parsed
|
||||
.segments
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, segment)| segment_item(segment, id, index))
|
||||
.collect::<Vec<_>>();
|
||||
if items.is_empty() {
|
||||
items.push(OutputItem::Text {
|
||||
deltas: vec![String::new()],
|
||||
});
|
||||
}
|
||||
Ok((items, notes))
|
||||
}
|
||||
|
||||
/// The output item of one parsed segment; a call gets the id `call_<response>_<index>`.
|
||||
fn segment_item(segment: Segment, id: &str, index: usize) -> OutputItem {
|
||||
match segment {
|
||||
Segment::Text(text) => OutputItem::Text { deltas: vec![text] },
|
||||
Segment::Call { name, arguments } => OutputItem::FunctionCall {
|
||||
name,
|
||||
call_id: format!("call_{}_{}", &id[5..], index),
|
||||
argument_deltas: vec![arguments.to_string()],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The request's tool declarations in the form the parser reads; none when the request declares no tools.
|
||||
pub fn flat_tools(request: &CreateRequest) -> Vec<Value> {
|
||||
Catalog::new(&request.tools)
|
||||
.map(|catalog| catalog.flat)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//! The tool declarations of a request in the form the answer readers take.
|
||||
|
||||
use crate::responses::request::CreateRequest;
|
||||
use leleka_gateway_text::response_tools::Catalog;
|
||||
use serde_json::Value;
|
||||
|
||||
/// The request's tool declarations in the form the parser reads; none when the request declares no tools.
|
||||
pub fn flat_tools(request: &CreateRequest) -> Vec<Value> {
|
||||
Catalog::new(&request.tools)
|
||||
.map(|catalog| catalog.flat)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! The samplers of a request that the worker of some models cannot carry, and what the gateway does about them.
|
||||
|
||||
use crate::responses::request::CreateRequest;
|
||||
use leleka_sampler_ref::RequestSampling;
|
||||
|
||||
/// A sampler of a request that the worker of some models cannot carry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Sampler {
|
||||
TopK,
|
||||
MinP,
|
||||
RepetitionPenalty,
|
||||
FrequencyPenalty,
|
||||
PresencePenalty,
|
||||
}
|
||||
|
||||
impl Sampler {
|
||||
/// The name of the request field, as an error names it.
|
||||
pub fn param(self) -> &'static str {
|
||||
match self {
|
||||
Self::TopK => "top_k",
|
||||
Self::MinP => "min_p",
|
||||
Self::RepetitionPenalty => "repetition_penalty",
|
||||
Self::FrequencyPenalty => "frequency_penalty",
|
||||
Self::PresencePenalty => "presence_penalty",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a model's worker cannot sample: the samplers, in the order they are checked, and the words of the error a
|
||||
/// client gets for asking for one of them.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct SamplingLimit {
|
||||
pub unsupported: &'static [Sampler],
|
||||
pub message: &'static str,
|
||||
}
|
||||
|
||||
/// Whether the request sets the sampler to something other than its neutral value.
|
||||
fn is_set(sampler: Sampler, sampling: &RequestSampling) -> bool {
|
||||
match sampler {
|
||||
Sampler::TopK => sampling.top_k.is_some(),
|
||||
Sampler::MinP => sampling.min_p.is_some(),
|
||||
Sampler::RepetitionPenalty => sampling.repetition_penalty.is_some_and(|v| v != 1.0),
|
||||
Sampler::FrequencyPenalty => sampling.frequency_penalty.is_some_and(|v| v != 0.0),
|
||||
Sampler::PresencePenalty => sampling.presence_penalty.is_some_and(|v| v != 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first sampler the request sets that the model's worker cannot carry.
|
||||
pub fn unsupported_sampler(
|
||||
sampling: &RequestSampling,
|
||||
limit: &SamplingLimit,
|
||||
) -> Option<&'static str> {
|
||||
let set = limit
|
||||
.unsupported
|
||||
.iter()
|
||||
.find(|sampler| is_set(**sampler, sampling));
|
||||
set.map(|sampler| sampler.param())
|
||||
}
|
||||
|
||||
/// Remove the samplers the model's worker cannot carry from the request (the server defaults must not reach it).
|
||||
pub fn drop_unsupported_samplers(request: &mut CreateRequest, limit: &SamplingLimit) {
|
||||
for sampler in limit.unsupported {
|
||||
match sampler {
|
||||
Sampler::TopK => request.top_k = None,
|
||||
Sampler::MinP => request.min_p = None,
|
||||
Sampler::RepetitionPenalty => {
|
||||
request.repetition_penalty = None;
|
||||
request.penalty_last_n = None;
|
||||
}
|
||||
Sampler::FrequencyPenalty => request.frequency_penalty = None,
|
||||
Sampler::PresencePenalty => request.presence_penalty = None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Unit tests of the sampler limit.
|
||||
|
||||
use super::*;
|
||||
|
||||
const LIMIT: SamplingLimit = SamplingLimit {
|
||||
unsupported: &[
|
||||
Sampler::TopK,
|
||||
Sampler::RepetitionPenalty,
|
||||
Sampler::PresencePenalty,
|
||||
],
|
||||
message: "limited",
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn the_first_unsupported_sampler_that_is_set_is_named() {
|
||||
let neutral = RequestSampling {
|
||||
repetition_penalty: Some(1.0),
|
||||
presence_penalty: Some(0.0),
|
||||
min_p: Some(0.1),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(unsupported_sampler(&neutral, &LIMIT), None);
|
||||
let set = RequestSampling {
|
||||
presence_penalty: Some(0.5),
|
||||
repetition_penalty: Some(1.1),
|
||||
..neutral
|
||||
};
|
||||
assert_eq!(
|
||||
unsupported_sampler(&set, &LIMIT),
|
||||
Some("repetition_penalty")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unsupported_samplers_leave_the_request() {
|
||||
let mut request: CreateRequest = serde_json::from_value(
|
||||
serde_json::json!({"model": "m", "input": "x", "top_k": 5, "min_p": 0.1, "repetition_penalty": 1.2,
|
||||
"penalty_last_n": 64, "frequency_penalty": 0.3}),
|
||||
)
|
||||
.unwrap();
|
||||
drop_unsupported_samplers(&mut request, &LIMIT);
|
||||
assert_eq!(request.top_k, None);
|
||||
assert_eq!(request.repetition_penalty, None);
|
||||
assert_eq!(request.penalty_last_n, None);
|
||||
assert_eq!(request.min_p, Some(0.1));
|
||||
assert_eq!(request.frequency_penalty, Some(0.3));
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! The `</think>` marker that ends a reasoning block, as the readers and the reasoning budget look for it.
|
||||
|
||||
pub(crate) const THINK_END: &str = "</think>";
|
||||
|
||||
/// The offset of the first marker in `bytes`.
|
||||
pub(crate) fn find_end(bytes: &[u8]) -> Option<usize> {
|
||||
bytes
|
||||
.windows(THINK_END.len())
|
||||
.position(|part| part == THINK_END.as_bytes())
|
||||
}
|
||||
|
||||
/// How many bytes at the end of `bytes` may be the start of a marker still arriving: the longest proper prefix of
|
||||
/// the marker that `bytes` ends with.
|
||||
pub(crate) fn held_prefix_len(bytes: &[u8]) -> usize {
|
||||
(1..THINK_END.len())
|
||||
.rev()
|
||||
.find(|length| bytes.ends_with(&THINK_END.as_bytes()[..*length]))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
@@ -90,7 +90,7 @@ is the composition root of the gateway process (`serve()` in `control-plane/src/
|
||||
| EngineFamily + `spawn::<F>` | `leleka_engine_core::family::{EngineFamily, spawn}`; families `Qwen35Cuda` and `EngineFake` | `F` is generic; the result is `Box<dyn Backend>` | the root is monomorphised over the family; the trait object is the process boundary |
|
||||
| Backend | `leleka_backend_api::Backend` (`crates/backend-api/src/lib.rs`) | `Box<dyn Backend>` in `RuntimeServer` (`desktop-core`) | methods are request-level (`load`, `start_generation`, `cancel`, `unload`, reports); tokens travel in the `GenerationStream` |
|
||||
| Gateway ports | `EngineClient`, `ResponseStore`, `Clock`, `ToolHub`, `VisionEncoder` (`control-plane/src/ports/`) | `Arc<dyn Port>` in `AppState`, boxed futures | called once per request or per process; streaming loops read the plain `mpsc` receiver |
|
||||
| OutputDecoder | `leleka_gateway_domain::output::{OutputDecoder, OutputEvent}`, made by `TextCodec::output_decoder` (`output-event.md`) | enum over the families (`Qwen`, `Harmony`); no virtual call per token | one decoder per generation; the adapters of the families produce the canonical `OutputEvent` that the Responses answers consume |
|
||||
| OutputDecoder | `leleka_gateway_domain::output::{LiveDecoder, AtEndDecoder, OutputEvent}`, made by `TextCodec::live_decoder` and `at_end_decoder` (`output-event.md`) | enum over the families (`Qwen`, `Harmony`) behind two decoder types; no virtual call per token | one decoder per generation; the adapters of the families produce the canonical `OutputEvent` that the Responses answers consume |
|
||||
|
||||
Inside the Qwen3.5 adapter there are three more device traits, all crate-private: `RequestOwners` (admission to finish), `PrefixDevice`
|
||||
(the prefix cache) and `OriginalServePort` (the verify round). The rule behind the table is the `dyn-trait` pattern in
|
||||
|
||||
@@ -39,9 +39,9 @@ wrote that markup.
|
||||
| Site | What it did | After S23 |
|
||||
|---|---|---|
|
||||
| `gateway-domain/responses/effort.rs` `reasoning_enabled(request, family)` | `family == GptOss` means always reasoning; used by `text.rs` (which stream), `buffered.rs`, `answer.rs`, `reasoning.rs` | `reasoning_enabled(request, codec)` reads `TextCodec::always_reasons()` |
|
||||
| `responses/create/admit.rs` `check_live_features` | gpt-oss: refuse samplers the worker `GEN` line lacks | `TextCodec::sampling_limit()` (the message is the family's) |
|
||||
| `responses/create/admit.rs` `apply_sampling_defaults` | gpt-oss: drop the samplers it lacks | the same capability |
|
||||
| `responses/stream/*.rs`, `create/answer.rs` | `tokenizer.decoder()` bytes, then `</think>` and `<tool_call>` scanning in each loop | `TextCodec::output_decoder(plan)` returns `OutputDecoder`; the loops read `OutputEvent` |
|
||||
| `responses/create/admit.rs` `check_live_features` | gpt-oss: refuse samplers the worker `GEN` line lacks (a hard-coded field list in `effort.rs`) | `TextCodec::sampling_limit()` returns the set of samplers and the message; `sampler_limit::unsupported_sampler` reads it |
|
||||
| `responses/create/admit.rs` `apply_sampling_defaults` | gpt-oss: drop the samplers it lacks (a second hard-coded list) | `sampler_limit::drop_unsupported_samplers` reads the same set |
|
||||
| `responses/stream/*.rs`, `create/answer.rs` | `tokenizer.decoder()` bytes, then `</think>` and `<tool_call>` scanning in each loop | `TextCodec::live_decoder` / `at_end_decoder`; the loops read `OutputEvent` |
|
||||
| `responses/intake/parts.rs` `render_prompt` | `match family`: ChatML template with control-token marks, or the Harmony renderer | unchanged (input side, see below) |
|
||||
| `responses/intake.rs` `expand_images` | needs the Qwen tokenizer (`qwen()`) for pictures | unchanged (input side) |
|
||||
| `responses/reasoning.rs` `reasoning_plan` | reasoning budget uses the Qwen tokenizer (`qwen()`) | unchanged (Qwen-only feature) |
|
||||
@@ -59,68 +59,128 @@ OutputEvent::Reasoned { text, complete, tokens } the reasoning of the respon
|
||||
OutputEvent::Text(String) answer text
|
||||
OutputEvent::Call { name, arguments: Value } one whole call of a declared tool
|
||||
|
||||
OutputError::Decode(msg) the ids could not be read, or the reasoning never ended -> 502 detokenization_failed
|
||||
OutputError::Parse(msg) a tool call in the text is not acceptable -> 502 tool_call_parse_failed
|
||||
OutputError::Decode(msg) the ids could not be read, the reasoning never ended, or the generation already ended -> 502 detokenization_failed
|
||||
OutputError::Parse(msg) a tool call in the text is not acceptable -> 502 tool_call_parse_failed
|
||||
```
|
||||
|
||||
`TextCodec::output_decoder(ReadPlan) -> OutputDecoder`. `OutputDecoder` is an enum over the families (`Bytes::Qwen`,
|
||||
`Bytes::Harmony`), so a token costs a `match`, not a virtual call. Two readings, chosen by the consumer:
|
||||
A family hands out one decoder per generation and per reading: `TextCodec::live_decoder(LivePlan) -> LiveDecoder` and
|
||||
`TextCodec::at_end_decoder(AtEndPlan) -> AtEndDecoder`. Both sit on the same private `TokenBytes` enum (`Qwen`, `Harmony`), so a
|
||||
token costs a `match`, not a virtual call, and what one reading offers cannot be asked of the other. `live_decoder` has the default
|
||||
`None`: a model that always reasons (gpt-oss) is read at its end, and the two live streams fail the response if they are ever given
|
||||
`None`:
|
||||
|
||||
* `ReadPlan::Live(LivePlan { tools, recovery, keep_raw })`: text and whole calls as the bytes arrive (UTF-8 completion, then
|
||||
`tool_output::Incremental`). Every event of `push` and `finish` is final. Used by the plain-text stream and the tool-call stream.
|
||||
* `ReadPlan::AtEnd(AtEndPlan { reasoning, tools, recovery, keep_raw })`: the answer is read once the generation is over.
|
||||
`push` returns only `ReasoningDelta` previews; `finish(Finish)` returns the events that make up the response (`Reasoned`, then
|
||||
`Text` and `Call` as `tool_output::parse_with` reads them, or one `Text` when the request declared no tools). Used by the buffered
|
||||
stream and the buffered answer. The two readings stay apart because the incremental and the batch tool-call readers are not the
|
||||
same function (a `</function>` left out is accepted only at the end).
|
||||
* `LiveDecoder` (`LivePlan { tools, recovery, keep_raw }`): text and whole calls as the bytes arrive (UTF-8 completion, then
|
||||
`tool_output::Incremental`). Every event of `push` and `finish` is final; `finish` also takes the bytes the family held back.
|
||||
Accessors: `notes()` and `raw_text()`. Used by the plain-text stream and the tool-call stream.
|
||||
* `AtEndDecoder` (`AtEndPlan { reasoning, preview, tools, recovery, keep_raw }`): the answer is read once the generation is over.
|
||||
`push` returns only `ReasoningDelta` previews (none when `preview` is off, which the buffered answer sets: nobody watches it);
|
||||
`finish(Finish)` returns the events that make up the response (`Reasoned`, then `Text` and `Call` as `tool_output::parse_with`
|
||||
reads them, or one `Text` when the request declared no tools; an answer always has at least one text event). Accessors:
|
||||
`notes()`, `accepted_call_in_reasoning()`, `split_text()`. Used by the buffered stream and the buffered answer. The two readings
|
||||
stay apart because the incremental and the batch tool-call readers are not the same function (a `</function>` left out is
|
||||
accepted only at the end).
|
||||
|
||||
`output_items(events, response_id)` turns the events into `OutputItem`s and the reasoning token count. `OutputDecoder` also exposes
|
||||
what the callers log: `notes()` (calls accepted beyond the template form), `accepted_call_in_reasoning()`, `raw_text()` and
|
||||
`split_text()` (the debug copy of a failed output, only when `keep_raw`).
|
||||
A generation ends once: `push` or `finish` after `finish` is a decode error (in the buffered stream it is a `response.failed`, not a
|
||||
panic). `output_items(events, response_id)` turns the events into `OutputItem`s and the reasoning token count. The cut of a finished
|
||||
generation into reasoning and answer is text-level code in `output/cut.rs` (`cut_text`, one `CutGeneration`, also exposed as
|
||||
`cut_reasoning_for_corpus` for the tool corpus tests; the tokens are counted from its `extent`); the `</think>` search and hold-back are in `think_marker.rs`, used by the reasoning previewer, the cut and the
|
||||
reasoning budget.
|
||||
|
||||
A new family implements its bytes (or events) behind a new `OutputDecoder` arm and states `always_reasons()` and `sampling_limit()`;
|
||||
no consumer changes.
|
||||
Adding a family touches, for the output side: a `TokenBytes` arm and the constructors `LiveDecoder::<family>` and
|
||||
`AtEndDecoder::<family>`, all inside `gateway-domain` (the enum is private to it, so those constructors are the only way in); a
|
||||
`TextCodec` implementation in the crate that holds the family's tokenizer (`harmony_family.rs` in `strata-control` for gpt-oss) with
|
||||
`at_end_decoder`, `live_decoder` only if the family can be read live, `always_reasons`, `sampling_limit`, `terminal_ids`, `encode` and
|
||||
`family()` (a `Family` variant); and the choice of the codec in `serve/state.rs`. The stream loops and the answer builder do not
|
||||
change. The input side (`render_prompt`, pictures, the reasoning budget) still has its own `Family` and `qwen()` branches.
|
||||
|
||||
## Migrated sites
|
||||
|
||||
| Step | Site | What it reads |
|
||||
|---|---|---|
|
||||
| golden | `responses/tests/output_golden.rs`, `tests/fixtures/golden/output_{cases,events}.json` | the proof harness (below) |
|
||||
| 1 | `stream/text.rs` | `Live`, no tools: `Text` |
|
||||
| 2 | `stream/tool_run.rs`, `stream/tools.rs` | `Live`, tools: `Text`, `Call` |
|
||||
| 3 | `create/answer.rs`, `tool_recovery.rs` (`at_end_plan`, `finish_output`) | `AtEnd`: all events |
|
||||
| 4 | `stream/buffered.rs` | `AtEnd`: `ReasoningDelta` live, the rest at DONE |
|
||||
| golden | `control-plane/tests/output_golden/`, `tests/fixtures/golden/output_{cases,events}.json` | the proof harness (below) |
|
||||
| 1 | `stream/text.rs` | live, no tools: `Text` |
|
||||
| 2 | `stream/tool_run.rs`, `stream/tools.rs` | live, tools: `Text`, `Call` |
|
||||
| 3 | `create/answer.rs`, `tool_recovery.rs` (`at_end_plan`, `finish_generation`) | at end: all events |
|
||||
| 4 | `stream/buffered.rs` | at end: `ReasoningDelta` live, the rest at DONE |
|
||||
| 5 | `reasoning_enabled`, `admit.rs` | `TextCodec::always_reasons`, `sampling_limit` |
|
||||
| 6 | the replaced readers | `decode_generation_noted`, `decoded_items`, `ReasoningStream`, `drain_utf8` copies removed |
|
||||
| 7 | the first review | live and at-end decoder types, `TokenDecoder` and the legacy item builder removed, the tool corpus on the gateway's cut, the sampler set |
|
||||
| 8 | the second review | names, one `CutGeneration`, `sampler_limit.rs`, no gpt-oss live reading, 29 more golden cases and the tests of the store, the worker's sampling and the disconnect at `DONE` |
|
||||
|
||||
## Identity proof
|
||||
|
||||
`responses::tests::output_golden` drives the real `create` handler with 66 scripted token sequences (37 Qwen3.5, 29 gpt-oss) in both modes
|
||||
(stream and buffered), 132 captures, and compares status, content type and body bytes (SSE framing included; ids made of the clock and
|
||||
a counter, and timestamps, are replaced) with `output_events.json`. The scripts cover: plain text, multi-byte text split over tokens,
|
||||
a terminal token followed by more tokens, tools with text, one call, two calls, unknown tool, schema violation, an unfinished call
|
||||
at the length limit, a missing closer, a custom tool, reasoning that closes, reasoning that never closes (length and natural stop),
|
||||
reasoning that ends on whole calls, structured output valid and invalid, worker failures at the start and in the middle (also a memory
|
||||
refusal), and for gpt-oss: analysis and final, final only, analysis only, a cut analysis, calls with and without analysis, preamble
|
||||
and two calls, calls without declared tools, unknown tool, schema violation, invalid JSON, a non-object, a bad argument name, empty
|
||||
arguments, a cut call, two finals, analysis after the answer, multi-byte text, trailing newlines. The captures were recorded on
|
||||
`cbc1a9587` and have not been rewritten since. Scripts are synthetic.
|
||||
`control-plane/tests/output_golden` (a test binary of its own, because the cases switch the process-wide tool-call recovery) drives
|
||||
the real `create` handler with 159 scripted token sequences, each as a stream and as a buffered answer: 318 captures of status,
|
||||
content type and body bytes, SSE framing included. **The expected captures were recorded on `08afbf216`** (`cbc1a9587`, the code before
|
||||
S23, plus the first harness) in a temporary worktree, and are checked against the new code; none was recorded on it and none differs. `regenerate_output_golden`
|
||||
refuses to run unless `OUTPUT_GOLDEN_RECORD` names the pre-S23 commit and the tree has no `output` module, and
|
||||
`output_events.recorded_on` names the commit the captures were recorded on (a test pins it).
|
||||
|
||||
Results: the golden passed unchanged after each migration step. `cargo test --no-fail-fast --all-targets` for `strata-control`,
|
||||
`leleka-gateway-domain`, `leleka-gateway-text`, `leleka-harmony`, `leleka-tokenizer` and `leleka-runtime-client` on Linux (WSL), before
|
||||
(`cbc1a9587`) and after, compared with `scripts/dev/test-outcomes.py compare`: 0 missing, 0 outcome changes, 13 new ids (10 unit
|
||||
tests of `output/` in `leleka-gateway-domain`, the two golden tests and the ignored `regenerate_output_golden`); 515 ok / 1 ignored
|
||||
before, 527 ok / 2 ignored after. The tests that read the replaced code (`reasoning_marker_and_unicode_split_at_every_byte`, the
|
||||
unclosed-reasoning test, the utf8 test) keep their ids and now read through the new decoder. `cargo check --all-targets` and
|
||||
`cargo clippy --no-deps --all-targets -- -D warnings` for `strata-control` and `leleka-gateway-domain`: 0 warnings. `rustfmt --check`
|
||||
on the changed files: no diff. `check-limits.py --base origin/claude/hexagonal-integ`, `check-architecture.py` and
|
||||
`check-ci-coverage.py`: green; `architecture-baseline.json` tightened (`dyn-trait` gateway-domain 5 to 4, strata-control 14 to 12).
|
||||
No performance claim is made: the buffered readings now decode each token as it arrives instead of once at the end, which was
|
||||
not measured.
|
||||
Volatile text is normalised so that nothing identity-relevant is lost: every distinct id becomes `<kind>_ID<k>` by order of first
|
||||
appearance and **keeps its numeric suffix** (`call_ID3_1`), so the index inside `call_<response>_<n>` is pinned, and
|
||||
`two_calls_of_one_response_have_different_call_ids` checks the call ids Codex pairs tool outputs by; timestamps become 0.
|
||||
|
||||
## Behaviours kept on purpose
|
||||
The scripts cover: plain text; a terminal token followed by more tokens (also with reasoning, tools and structured output on); tools
|
||||
with text, one call, two calls, unknown tool, schema violation, an unfinished call at the length limit, a missing closer, a custom
|
||||
tool; reasoning that closes, that never closes (length and natural stop), that ends on whole calls, that closes and is followed by a
|
||||
call cut at the length limit; the request's `max_output_tokens` reached in every reading; a second `</think>` in the answer and inside a tool argument; structured output valid and invalid, also with reasoning on and for gpt-oss, also with tools; namespaced tools; `DONE` before the first
|
||||
token and an error after `DONE`; a worker that reports fewer generated tokens than the reasoning took (the clamp of the reasoning
|
||||
tokens); the
|
||||
tool-call recovery on and off with two drifted forms in the live tool stream, the buffered stream and the buffered answer; non-ASCII
|
||||
call arguments, also as multi-byte tokens; **a vocabulary with multi-byte tokens** (a euro sign, an emoji, a token holding the whole
|
||||
`</think>` and a token that ends in the middle of it, with `reasoning_tokens` asserted: 2 and 3) and raw byte tokens; characters cut
|
||||
at the length limit and at stop in the live text, the live tool stream, the reasoning preview, the structured stream and gpt-oss
|
||||
channels; a lone continuation byte in reasoning and in the answer; an id outside the vocabulary in the middle of a script; a source
|
||||
that closes without `DONE`; `Finish::Cancel`; worker failures (also a memory refusal); and for gpt-oss the analysis, commentary and
|
||||
final channels in their combinations, calls with and without declared tools, invalid arguments and the rest of the earlier list.
|
||||
Scripts are synthetic.
|
||||
|
||||
These are in the golden, so the migration could not change them silently:
|
||||
Timing, which captures cannot show: with a worker that waits for a gate before `DONE`, the first `response.reasoning_text.delta`
|
||||
(both families), the first text delta and the first whole call reach the client before `DONE` is sent; a client that leaves closes the
|
||||
source in five stream modes, and also when it leaves at `DONE`; a stored response equals the one the client was sent (streamed and
|
||||
not); a gpt-oss request that sets a sampler the worker lacks gets a 400 that names the first one; the server defaults for those
|
||||
samplers do not reach the gpt-oss worker (top_k 20 and penalty_last_n 64 among them), neutral values are accepted, and Qwen keeps all
|
||||
five samplers. All fifteen tests of the binary pass on `08afbf216` and on the new code.
|
||||
|
||||
Results on the tip: `cargo test --no-fail-fast --all-targets` for `strata-control`, `leleka-gateway-domain`, `leleka-gateway-text`,
|
||||
`leleka-harmony`, `leleka-tokenizer` and `leleka-runtime-client` on Linux (WSL), before (`cbc1a9587`) and after, compared with
|
||||
`scripts/dev/test-outcomes.py compare`: 0 missing, 0 outcome changes, 38 new ids; 515 ok / 1 ignored before, 552 ok / 2 ignored
|
||||
after. The ids of the first golden harness moved to the new binary; the tests that read the replaced code (`reasoning_marker_and_unicode_split_at_every_byte`,
|
||||
the unclosed-reasoning test, the utf8 test, the Harmony decoder tests) keep their ids and now read through the new decoders.
|
||||
`cargo check --all-targets` and `cargo clippy --no-deps --all-targets -- -D warnings` for `strata-control` and `leleka-gateway-domain`:
|
||||
0 warnings. `check-limits.py --base origin/claude/hexagonal-integ`, `check-architecture.py` and `check-ci-coverage.py`: green;
|
||||
`architecture-baseline.json` tightened (`dyn-trait` gateway-domain 5 to 2, strata-control 14 to 11).
|
||||
|
||||
Not covered end to end: `STRATA_DEBUG_FAILED_OUTPUT` (read once per process through a `OnceLock`, so a test binary cannot switch it
|
||||
beside other tests); the `keep_raw`, `raw_text()` and `split_text()` paths have unit tests in `leleka-gateway-domain`.
|
||||
|
||||
## Behaviour that changed or moved
|
||||
|
||||
No response byte changes (the golden). What changes besides:
|
||||
|
||||
* **Decoding time.** Per-token decoding as the ids arrive is new only for the structured-output stream on Qwen (it kept the ids and
|
||||
decoded them at DONE); the reasoning stream already decoded every token as it arrived, and the buffered (non-stream) answer still
|
||||
decodes all ids at the end, inside `spawn_blocking`. A decode error therefore surfaces at the offending token in the structured
|
||||
stream and not at DONE; the failure code and message and every response byte are the same (the golden has an id outside the
|
||||
vocabulary in `q-structured-oov-id` and the other modes).
|
||||
* **The `post_decode` stage** (`buffered.rs`, `docs/cp-latency.md`, `scripts/cp/summarize.py`) now times only `finish` (the cut and the
|
||||
batch parse), because the bytes are decoded as they arrive. It is not comparable with numbers measured before S23.
|
||||
* **Logs.** A refused tool call in the buffered stream now also writes the `STRATA_DEBUG_FAILED_OUTPUT` debug copy to stderr when that
|
||||
variable is set (the non-stream answer already did). In the non-stream answer the debug copy is written before the
|
||||
generation-failure line instead of after it.
|
||||
* **Flags are read at stream start.** The buffered stream builds its plan (tool-call recovery, debug copy) when the stream starts and
|
||||
not at DONE; the tool-call stream already read the recovery when it started. A recovery switch flipped during a request therefore
|
||||
no longer reaches that request's buffered stream (only the tests flip it).
|
||||
* **The worker sees an out-of-vocabulary id as a client that left.** In the structured-output stream on Qwen the new code fails at
|
||||
the offending token and drops the source then; `backend_worker/generation_run.rs` sees the closed result (`Wake::ClientGone`) and
|
||||
cancels the engine's generation at that point, and `conclude.rs` counts the request as `disconnected` (`metrics.rs`: outcome
|
||||
`disconnect`, `cancelled` plus one) where the code before S23 let the generation run to `DONE` and counted a finished generation with
|
||||
its stop or length. So the worker metrics of such a request differ (earlier cancel, `disconnect` instead of the finish reason) while
|
||||
the client sees the same `response.failed`. The reasoning stream and the live streams already behaved so for a decode or parse
|
||||
error.
|
||||
* **A generation ends once.** `finish` twice, or `push` after it, is a decode error.
|
||||
|
||||
Behaviours kept on purpose (they are in the golden):
|
||||
|
||||
* gpt-oss: a call when the request declares no tools is not an error: its markup stays in the answer text.
|
||||
* gpt-oss: invalid JSON, a non-object, or an argument name that cannot be passed on is a decode error (`detokenization_failed`) at
|
||||
@@ -131,17 +191,17 @@ These are in the golden, so the migration could not change them silently:
|
||||
text).
|
||||
* The index in `call_<response>_<n>` counts answer items in the buffered readings and all items in the tool-call stream, as before.
|
||||
* Reasoning tokens are the tokens up to the one that completed `</think>` (for gpt-oss, the one that closed the analysis).
|
||||
* gpt-oss: a literal `</think>` inside the analysis text ends the reasoning there, because the Harmony decoder writes markup that the
|
||||
shared cut reads (a latent defect, pinned by `g-two-markers-analysis`).
|
||||
|
||||
## Not done, and why
|
||||
|
||||
* **The gpt-oss adapter still writes the Qwen-style markup inside the decoder.** `HarmonyDecoder` (moved unchanged from
|
||||
`control-plane/src/harmony_family.rs` to `gateway-domain/src/output/harmony.rs`) turns Harmony messages into `</think>` and
|
||||
`<tool_call>` text, and the shared reader parses that. Reading the channels directly would change two corners that the golden
|
||||
pins: a `</think>` written inside the analysis text would stay reasoning instead of ending it, and the call-without-tools quirk
|
||||
above would need a decision. Both are behaviour changes, so they are left for a step with an owner decision.
|
||||
`control-plane/src/harmony_family.rs` to `gateway-domain/src/output/harmony.rs`; `push` and `finish` are its own methods now) turns
|
||||
Harmony messages into `</think>` and `<tool_call>` text, and the shared cut and parse read that. Reading the channels directly
|
||||
would change two corners that the golden pins: the `</think>` inside the analysis text above, and the call-without-tools quirk. Both
|
||||
are behaviour changes, so they are left for a step with an owner decision.
|
||||
* **Prompt rendering is still chosen by `Family`** (`intake/parts.rs`), and the picture expansion, the reasoning budget and the
|
||||
runtime backend still ask for the Qwen tokenizer (`qwen()`). They are the input side of the codec; they need a prompt-rendering
|
||||
port, not an output one.
|
||||
* **`TextCodec::decoder()` and `TokenDecoder`** remain (two `dyn` mentions in `gateway-domain`) because the Harmony tests and
|
||||
`decode_all` use them. They can go with the direct Harmony reading.
|
||||
* **`unsupported_gptoss_sampling`** keeps its name; it is selected by `sampling_limit()` now, and no longer by the family.
|
||||
* **`GptOssCodec` lives in `strata-control`** because it loads the BPE from a GGUF file; the decoder it hands out is in the domain.
|
||||
|
||||
@@ -430,18 +430,17 @@ What changed in the move, apart from `pub(super)` becoming `pub`:
|
||||
|
||||
## OutputEvent and the output decoders (STRA-338 S23)
|
||||
|
||||
`crates/gateway-domain/src/output/` is new (pure, L2): `event.rs` (`OutputEvent`, `OutputError`), `decoder.rs` (`OutputDecoder`, the
|
||||
plans), `live.rs` and `at_end.rs` (the two readings), `harmony.rs` (the gpt-oss decoder, moved unchanged from
|
||||
`control-plane/src/harmony_family.rs`), `reasoning_split.rs`, `utf8.rs`, `fold.rs` (`output_items`). The four consumers in
|
||||
`strata-control` read events; `docs/architecture/output-event.md` has the flow analysis, the table of the sites that asked for the
|
||||
family, the identity proof and the list of behaviours kept on purpose. What it did not do:
|
||||
`crates/gateway-domain/src/output/` is new (pure, L2): `event.rs` (`OutputEvent`, `OutputError`), `token_bytes.rs` (the family's bytes),
|
||||
`live.rs` (`LiveDecoder`) and `at_end.rs` (`AtEndDecoder`) with `cut.rs` (the cut of a finished generation), `harmony.rs` (the
|
||||
gpt-oss decoder, moved from `control-plane/src/harmony_family.rs`), `reasoning_preview.rs`, `utf8.rs`, `fold.rs` (`output_items`); the
|
||||
`</think>` marker is `think_marker.rs`; the sampler limit of a worker is `sampler_limit.rs`. The four consumers in `strata-control` read events; `docs/architecture/output-event.md` has
|
||||
the flow analysis, the table of the sites that asked for the family, the identity proof, the behaviour changes and the list of what
|
||||
was kept on purpose. What it did not do:
|
||||
|
||||
| Left | Why | Removes it |
|
||||
|---|---|---|
|
||||
| `HarmonyDecoder` writes Qwen-style markup that the shared reader parses | reading the channels directly changes a `</think>` inside the analysis text and the calls-without-tools quirk; both are pinned by the golden | an owner decision, then one `OutputDecoder` arm that emits events |
|
||||
| `TextCodec::decoder()`, `TokenDecoder`, `decode_all` (two `dyn` mentions) | the Harmony unit tests and `GptOssCodec::decoder` use them | the direct Harmony reading |
|
||||
| `HarmonyDecoder` writes Qwen-style markup that the shared cut and parse read | reading the channels directly changes a `</think>` inside the analysis text and the calls-without-tools quirk; both are pinned by the golden | an owner decision, then one `Bytes` arm that emits events |
|
||||
| `intake/parts.rs` `render_prompt` still matches `Family`; `qwen()` for pictures, the reasoning budget and the runtime backend | input side of the codec | a prompt-rendering port |
|
||||
| `unsupported_gptoss_sampling` is named after the family | renaming touches the public re-export | rename with the prompt port |
|
||||
| `GptOssCodec` lives in `strata-control` | it holds the BPE loaded from a GGUF file (`std::fs`), which the pure domain may not read | none needed; the decoder it hands out is in the domain |
|
||||
|
||||
## strata-control `responses/` (STRA-338 S6, rest)
|
||||
|
||||
Reference in New Issue
Block a user