diff --git a/atom/mesh/src/observability/route_trace.rs b/atom/mesh/src/observability/route_trace.rs index 9a9e2807536..55be3690916 100644 --- a/atom/mesh/src/observability/route_trace.rs +++ b/atom/mesh/src/observability/route_trace.rs @@ -142,6 +142,23 @@ pub(crate) async fn estimated(attempts: F) -> (F::Output, Option .await } +/// Drops the estimate of `pool`'s selection unless the request is sent to the selected +/// `worker`: DP ranks keep separate KV caches, so a remapped request loses it. +pub(crate) fn keep_estimate_for(pool: &'static str, worker: &Arc) { + if !computes_prompt(pool) { + return; + } + let _ = ESTIMATE.try_with(|estimate| { + let mut estimate = estimate.borrow_mut(); + if estimate + .as_ref() + .is_some_and(|e| e.worker.url() != worker.url()) + { + *estimate = None; + } + }); +} + fn computes_prompt(pool: &'static str) -> bool { matches!( pool, @@ -170,18 +187,7 @@ pub(crate) fn record_estimate( /// Records the worker a request is sent to after rank mapping. pub(crate) fn record_dispatch(pool: &'static str, worker: &Arc) { MeshMetrics::record_selected_dp_rank(pool, worker.base_url(), worker.dp_rank()); - if computes_prompt(pool) { - let _ = ESTIMATE.try_with(|estimate| { - let mut estimate = estimate.borrow_mut(); - // DP ranks keep separate KV caches, so a remapped request loses the estimate. - if estimate - .as_ref() - .is_some_and(|e| e.worker.url() != worker.url()) - { - *estimate = None; - } - }); - } + keep_estimate_for(pool, worker); let _ = TRACE.try_with(|trace| { let selections = trace.selections.borrow(); let selection = selections.iter().find(|selection| selection.pool == pool); diff --git a/atom/mesh/src/routers/grpc/completion_adapter.rs b/atom/mesh/src/routers/grpc/completion_adapter.rs index 2040fe6c775..a57d30ef4cc 100644 --- a/atom/mesh/src/routers/grpc/completion_adapter.rs +++ b/atom/mesh/src/routers/grpc/completion_adapter.rs @@ -22,7 +22,10 @@ use crate::{ generate::{GenerateFinishReason, GenerateRequest, GenerateResponse}, sampling_params::SamplingParams, }, - routers::comm::error, + routers::{ + comm::error, + render::atom_usage::{self, AtomUsage}, + }, }; /// Build a synthetic SGLang `GenerateRequest` from an OpenAI `CompletionRequest`. @@ -117,6 +120,16 @@ pub(crate) fn completion_to_generate(c: &CompletionRequest) -> Result GenerateRequest { + GenerateRequest { + return_logprob: Some(false), + top_logprobs_num: None, + ..generate + } +} + /// Convert a list of native `GenerateResponse`s into an OpenAI `CompletionResponse`. fn build_completion_response(gens: Vec, model: String) -> CompletionResponse { let id = gens @@ -204,8 +217,18 @@ pub(crate) async fn wrap_generate_response_as_completion( } }; + // An ATOM worker's sequences carry their timing, which its usage reports. + let meta_infos = meta_infos(&bytes); + let atom = AtomUsage::of_meta_infos(&meta_infos.iter().collect::>()); + let completion = build_completion_response(gens, model); - let json = match serde_json::to_vec(&completion) { + let json = match atom { + None => serde_json::to_vec(&completion), + Some(atom) => atom + .extend_response(&completion, atom_usage::COMPLETION) + .and_then(|value| serde_json::to_vec(&value)), + }; + let json = match json { Ok(v) => v, Err(e) => { return error::internal_error( @@ -224,6 +247,18 @@ pub(crate) async fn wrap_generate_response_as_completion( new } +/// A generate response's `meta_info` alone; its text, ids and logprobs are skipped. +#[derive(serde::Deserialize)] +struct MetaInfoOnly { + meta_info: Option, +} + +/// Each response's `meta_info` in a `/generate` body, read without decoding the rest. +fn meta_infos(body: &[u8]) -> Vec { + let responses: Vec = serde_json::from_slice(body).unwrap_or_default(); + responses.into_iter().filter_map(|r| r.meta_info).collect() +} + /// Map a generate `finish_reason` Value (the raw JSON form, since streaming /// chunks are parsed loosely as Value to avoid coupling to a single schema) /// into the OpenAI completion `finish_reason` string. @@ -457,3 +492,19 @@ fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option { } haystack.windows(needle.len()).position(|w| w == needle) } + +#[cfg(test)] +mod meta_info_tests { + use super::*; + + #[test] + fn meta_infos_are_read_alone_and_responses_without_one_are_skipped() { + let body = json!([ + {"text": "a long reply", "output_ids": [1, 2], "meta_info": {"ttft": 0.5}}, + {"text": "no meta"}, + ]); + let read = meta_infos(&serde_json::to_vec(&body).unwrap()); + assert_eq!(read, [json!({"ttft": 0.5})]); + assert!(meta_infos(b"not json").is_empty()); + } +} diff --git a/atom/mesh/src/routers/grpc/engine/atom/pair.rs b/atom/mesh/src/routers/grpc/engine/atom/pair.rs index 77bf981bb97..8253f2511e7 100644 --- a/atom/mesh/src/routers/grpc/engine/atom/pair.rs +++ b/atom/mesh/src/routers/grpc/engine/atom/pair.rs @@ -29,7 +29,11 @@ use crate::core::placement::backend::BackendAdapter; use crate::core::placement::PlacementPlan; use crate::core::worker::RuntimeType; use crate::core::{Worker, WorkerLoadGuard, WorkerRegistry}; -use crate::observability::events::{Event, RequestPDSentEvent}; +use crate::observability::{ + events::{Event, RequestPDSentEvent}, + metrics::metrics_labels, + route_trace, +}; use crate::routers::grpc::engine::worker_client_cache::{get_grpc_client_from_worker, GrpcClient}; use crate::routers::prepare::generation_payload::GenerationPayload; use crate::routers::token_handle::engine_error::EngineError; @@ -243,6 +247,7 @@ impl AtomPairs { let started = Instant::now(); let prefill = apply_atom_pd_rank_mapping_policy(self.mapping, &self.workers, prefill.clone(), decode); + route_trace::keep_estimate_for(metrics_labels::WORKER_PREFILL, &prefill); let prefill_load = WorkerLoadGuard::new(prefill.clone(), None); let decode_load = WorkerLoadGuard::new(decode.clone(), None); RequestPDSentEvent { diff --git a/atom/mesh/src/routers/grpc/engine/atom/request.rs b/atom/mesh/src/routers/grpc/engine/atom/request.rs index 405dc275b5f..46b2af7bbf3 100644 --- a/atom/mesh/src/routers/grpc/engine/atom/request.rs +++ b/atom/mesh/src/routers/grpc/engine/atom/request.rs @@ -1,17 +1,17 @@ // SPDX-License-Identifier: MIT // Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. // Copyright (c) 2026 ATOM Project Contributors -//! A `GenerationPayload` as ATOM's GenerateRequest: the sampling fields ATOM's -//! HTTP routes read, stop strings and stop ids as token id sequences, and the -//! worker's DP rank. +//! A `GenerationPayload` as ATOM's GenerateRequest: the sampling fields ATOM's HTTP routes read, +//! stop strings and stop ids as token id sequences, the worker's DP rank and a chat's +//! StructuredOutput. use crate::atom_engine::{ - grpc::GenerateRequest, + grpc::{self, GenerateRequest}, wire::pb::{SamplingParams, TokenIds}, }; use crate::core::Worker; use crate::protocols::common::StringOrArray; -use crate::routers::prepare::generation_payload::GenerationPayload; +use crate::routers::prepare::generation_payload::{GenerationPayload, StructuredOutput}; use crate::routers::token_handle::engine_error::EngineError; use crate::tokenizer::traits::Tokenizer; @@ -63,12 +63,23 @@ pub(crate) fn generate_request( kv_transfer_params_json: None, data_parallel_rank: worker.dp_rank().map(|rank| rank as i32), stream: payload.stream, - structured_output: None, + structured_output: payload.structured_output.as_ref().map(structured_output), dp_session_id: payload.dp_session_id.clone(), dp_parent_session_id: payload.dp_parent_session_id.clone(), }) } +fn structured_output(carried: &StructuredOutput) -> grpc::StructuredOutput { + grpc::StructuredOutput { + tools_json: carried.tools_json.clone(), + tool_choice_json: carried.tool_choice_json.clone(), + response_format_json: carried.response_format_json.clone(), + chat_template_kwargs_json: carried.chat_template_kwargs_json.clone(), + prompt_opens_reasoning: carried.prompt_opens_reasoning, + message_tools_json: carried.message_tools_json.clone(), + } +} + /// Each stop string as ATOM encodes one, without special tokens, dropping a /// string that encodes to nothing. fn stop_token_sequences( diff --git a/atom/mesh/src/routers/grpc/engine/tests.rs b/atom/mesh/src/routers/grpc/engine/tests.rs index fb421c40d1c..0fd8c9f81dd 100644 --- a/atom/mesh/src/routers/grpc/engine/tests.rs +++ b/atom/mesh/src/routers/grpc/engine/tests.rs @@ -53,6 +53,7 @@ mod a_payload_to_proto { stream: false, return_hidden_states: false, log_metrics: false, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, @@ -820,6 +821,7 @@ mod e_engine_dispatch { stream: false, return_hidden_states: false, log_metrics: false, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, diff --git a/atom/mesh/src/routers/grpc/pd_router.rs b/atom/mesh/src/routers/grpc/pd_router.rs index 66785a596af..42dc62136a6 100644 --- a/atom/mesh/src/routers/grpc/pd_router.rs +++ b/atom/mesh/src/routers/grpc/pd_router.rs @@ -10,10 +10,11 @@ use tracing::debug; use super::engine::atom::pair::AtomPairs; use super::{ completion_adapter::{ - completion_to_generate, wrap_generate_response_as_completion, + completion_to_generate, without_logprobs, wrap_generate_response_as_completion, wrap_streaming_generate_as_completion, }, pipeline::Pipeline, + router::{atom_chat_refusal, atom_serves, logprobs_refused, media_refused}, }; use crate::{ app_context::AppContext, @@ -26,7 +27,11 @@ use crate::{ protocols::{ chat::ChatCompletionRequest, completion::CompletionRequest, generate::GenerateRequest, }, - routers::{comm::error, prepare, RouterTrait, SentChatBody}, + routers::{ + comm::error, + prepare::{self, inference::ParsedInference}, + RouterTrait, SentChatBody, + }, }; #[derive(Clone)] @@ -219,6 +224,14 @@ impl RouterTrait for GrpcPDRouter { body: &GenerateRequest, model_id: Option<&str>, ) -> Response { + if atom_serves(&self.worker_registry, model_id) { + if ParsedInference::generate_carries_media(body) { + return media_refused(); + } + if body.return_logprob == Some(true) { + return logprobs_refused(); + } + } self.route_generate_impl(headers, body, model_id).await } @@ -237,6 +250,9 @@ impl RouterTrait for GrpcPDRouter { sent: Option, model_id: Option<&str>, ) -> Response { + if let Some(refused) = atom_chat_refusal(&self.worker_registry, body, model_id) { + return refused; + } self.route_chat_impl(headers, body, model_id, sent).await } @@ -246,6 +262,9 @@ impl RouterTrait for GrpcPDRouter { body: &ChatCompletionRequest, model_id: Option<&str>, ) -> Response { + if let Some(refused) = atom_chat_refusal(&self.worker_registry, body, model_id) { + return refused; + } self.route_chat_impl(headers, body, model_id, None).await } @@ -256,6 +275,7 @@ impl RouterTrait for GrpcPDRouter { model_id: Option<&str>, ) -> Response { let synthetic = match completion_to_generate(body) { + Ok(g) if atom_serves(&self.worker_registry, model_id) => without_logprobs(g), Ok(g) => g, Err(msg) => return error::bad_request("completion_unsupported_field", msg), }; diff --git a/atom/mesh/src/routers/grpc/pipeline.rs b/atom/mesh/src/routers/grpc/pipeline.rs index 8dbf4f19837..9750de2ada7 100644 --- a/atom/mesh/src/routers/grpc/pipeline.rs +++ b/atom/mesh/src/routers/grpc/pipeline.rs @@ -1,8 +1,14 @@ //! Transport-neutral 4-step gRPC pipeline: prepare → plan → engine.dispatch → render. -use std::{sync::Arc, time::Instant}; +use std::{ + pin::Pin, + sync::Arc, + task::{ready, Context, Poll}, + time::Instant, +}; use axum::response::Response; +use futures::Stream; use http::HeaderMap; use tracing::error; @@ -18,9 +24,13 @@ use crate::{ traits::PdPlanner, types::{PlacementError, PlacementPlan, Protocol, RequestDescriptor}, }, - AttachedBody, WorkerLoadGuard, WorkerRegistry, UNKNOWN_MODEL_ID, + worker::RuntimeType, + AttachedBody, Worker, WorkerLoadGuard, WorkerRegistry, UNKNOWN_MODEL_ID, + }, + observability::{ + metrics::{bool_to_static_str, metrics_labels, MeshMetrics}, + route_trace, }, - observability::metrics::{bool_to_static_str, metrics_labels, MeshMetrics}, policies::PolicyRegistry, protocols::{ chat::{ChatCompletionRequest, ChatCompletionResponse}, @@ -38,9 +48,13 @@ use crate::{ stop_decoder_builder::create_stop_decoder, }, render, - token_handle::engine_error::EngineError, + token_handle::{ + engine_error::EngineError, + token_chunk::TokenChunk, + token_handle::{SourceClock, TokenHandle, TokenSource}, + }, }, - tokenizer::{traits::Tokenizer, StopSequenceDecoder}, + tokenizer::StopSequenceDecoder, }; #[derive(Clone)] @@ -48,52 +62,63 @@ pub(crate) struct Pipeline { planner: Arc, engine: Arc, backend_label: &'static str, - /// The ATOM bridge's: its output read as ATOM's Python server reads it - /// (`AtomOutput`). gRPC routing keeps its own reading. + /// Every output read as ATOM's servers read it (`AtomOutput`), whatever produced + /// it; otherwise only an ATOM worker's. atom_output: Option>, } -/// How ATOM's Python server reads the engine's output, where the router's -/// own reading differs: -/// - a chat the router renders has the channel opener its prompt ends on -/// read before the reply (`ResponseContext::prompt_opener`); -/// - the engine ends an output where a stop string's ids match and the -/// server returns all of it, so the router cuts at none of the stops; -/// - the server's decode leaves the model's end-of-sequence ids out of the -/// text, which the tiktoken decoder would not do by `skip_special_tokens`. +/// The label an ATOM worker lists its end-of-sequence ids under, GetModelInfo's. +const EOS_TOKEN_IDS_LABEL: &str = "eos_token_ids"; +/// The label, "true" or absent, of GetModelInfo's `usage_on_finish`. +const USAGE_ON_FINISH_LABEL: &str = "usage_on_finish"; + +/// ATOM's servers' reading of an output: the prompt's opener read first, no stop cut +/// (ATOM ends where a stop's ids match and returns it all), special tokens skipped and +/// end-of-sequence ids hidden. pub(crate) struct AtomOutput { end_token_ids: Vec, + /// A streamed chat's usage rides on its finish chunk. + usage_on_finish: bool, } impl AtomOutput { pub(crate) fn new(end_token_ids: Vec) -> Self { - Self { end_token_ids } + Self { + end_token_ids, + usage_on_finish: false, + } } - /// The request's decoder: none of its stops, and the end-of-sequence ids - /// hidden unless it asked to run past them. - fn stop_decoder(&self, ctx: &ResponseContext) -> StopSequenceDecoder { - let (skip_special_tokens, ignore_eos) = match &ctx.original { - ProtocolRequest::Chat(req) => (req.skip_special_tokens, req.ignore_eos), - ProtocolRequest::Generate(req) => { - let params = req.sampling_params.as_ref(); - ( - params.and_then(|p| p.skip_special_tokens).unwrap_or(true), - params.and_then(|p| p.ignore_eos).unwrap_or(false), - ) - } - }; - self.decoder(&ctx.tokenizer, skip_special_tokens, ignore_eos) + /// An ATOM worker's: the end-of-sequence ids and usage placement its GetModelInfo gave. + fn of_worker(worker: &dyn Worker) -> Self { + let labels = &worker.metadata().labels; + let listed = labels.get(EOS_TOKEN_IDS_LABEL); + Self { + usage_on_finish: labels + .get(USAGE_ON_FINISH_LABEL) + .is_some_and(|v| v == "true"), + ..Self::new( + listed + .and_then(|ids| serde_json::from_str(ids).ok()) + .unwrap_or_default(), + ) + } } - fn decoder( - &self, - tokenizer: &Arc, - skip_special_tokens: bool, - ignore_eos: bool, - ) -> StopSequenceDecoder { + /// The request's decoder: none of its stops, special tokens skipped whatever it asks + /// (as ATOM's HTTP routes decode), and the end-of-sequence ids hidden unless it asked + /// to run past them. + fn stop_decoder(&self, ctx: &ResponseContext) -> StopSequenceDecoder { + let ignore_eos = match &ctx.original { + ProtocolRequest::Chat(req) => req.ignore_eos, + ProtocolRequest::Generate(req) => req + .sampling_params + .as_ref() + .and_then(|p| p.ignore_eos) + .unwrap_or(false), + }; let end_token_ids = (!ignore_eos).then_some(&self.end_token_ids); - create_stop_decoder(tokenizer, None, end_token_ids, skip_special_tokens, false) + create_stop_decoder(&ctx.tokenizer, None, end_token_ids, true, false) } } @@ -111,17 +136,45 @@ impl Pipeline { } } - /// Read the output as ATOM's Python server reads it (`AtomOutput`). + /// Read every output as ATOM's servers read it (`AtomOutput`). + #[cfg_attr(not(test), allow(dead_code))] // for an in-process ATOM front end pub(crate) fn reading_output_as_atom(mut self, atom_output: AtomOutput) -> Self { self.atom_output = Some(Arc::new(atom_output)); self } - /// Give a prepared request the decoder `AtomOutput` reads with, if any. - fn read_as_atom(&self, ctx: &mut ResponseContext) { - if let Some(atom) = &self.atom_output { - ctx.stop_decoder = atom.stop_decoder(ctx); - } + /// Give a placed request the decoder `AtomOutput` reads with, if its producer's + /// output is ATOM's (D's for a pair); any other keeps the router's reading. + fn read_as_atom(&self, plan: &PlacementPlan, ctx: &mut ResponseContext) { + let producer = match plan { + PlacementPlan::Single { worker, .. } => worker, + PlacementPlan::Pair { decode, .. } => decode, + }; + let atom = match &self.atom_output { + Some(atom) => Arc::clone(atom), + None if producer.metadata().runtime_type == RuntimeType::Atom => { + take_parsers(producer.as_ref(), ctx); + Arc::new(AtomOutput::of_worker(producer.as_ref())) + } + None => { + ctx.prompt_opener = None; + return; + } + }; + ctx.stop_decoder = atom.stop_decoder(ctx); + ctx.reads_as_atom = true; + ctx.usage_on_finish = atom.usage_on_finish; + } +} + +/// The parsers an ATOM `worker` names (GetModelInfo's, or its registration's) where the +/// router names none, so the reply is not parsed by the model name it was requested under. +fn take_parsers(worker: &dyn Worker, ctx: &mut ResponseContext) { + if ctx.configured_reasoning_parser.is_none() { + ctx.configured_reasoning_parser = worker.reasoning_parser().map(str::to_string); + } + if ctx.configured_tool_parser.is_none() { + ctx.configured_tool_parser = worker.tool_parser().map(str::to_string); } } @@ -214,20 +267,10 @@ impl Pipeline { Ok(t) => t, Err(e) => return self.record_chat_err(&model, start, e), }; - self.read_as_atom(&mut resp_ctx); - let placement = match self.plan_for(&payload, &resp_ctx).await { - Ok(p) => p, + let (guards, stream) = match self.dispatch(&mut payload, &mut resp_ctx).await { + Ok(dispatched) => dispatched, Err(e) => return self.record_chat_err(&model, start, e), }; - let guards = self.load_guards(&placement, resp_ctx.headers.as_ref()); - let stream = match self - .engine - .dispatch_with_tokenizer(&placement, &mut payload, &resp_ctx.tokenizer) - .await - { - Ok(s) => s, - Err(e) => return self.record_chat_err(&model, start, engine_err_to_response(e)), - }; let is_stream = resp_ctx.original.is_streaming(); let response = if is_stream { @@ -274,26 +317,10 @@ impl Pipeline { Ok(t) => t, Err(e) => return self.record_generate_err(&model_for_metric, start, e), }; - self.read_as_atom(&mut resp_ctx); - let placement = match self.plan_for(&payload, &resp_ctx).await { - Ok(p) => p, + let (guards, stream) = match self.dispatch(&mut payload, &mut resp_ctx).await { + Ok(dispatched) => dispatched, Err(e) => return self.record_generate_err(&model_for_metric, start, e), }; - let guards = self.load_guards(&placement, resp_ctx.headers.as_ref()); - let stream = match self - .engine - .dispatch_with_tokenizer(&placement, &mut payload, &resp_ctx.tokenizer) - .await - { - Ok(s) => s, - Err(e) => { - return self.record_generate_err( - &model_for_metric, - start, - engine_err_to_response(e), - ) - } - }; let is_stream = resp_ctx.original.is_streaming(); let response = if is_stream { @@ -328,18 +355,48 @@ impl Pipeline { )); } - let (mut payload, resp_ctx) = prepare::prepare_chat(req, headers, model_id, &components)?; - let placement = self.plan_for(&payload, &resp_ctx).await?; - let _guards = self.load_guards(&placement, resp_ctx.headers.as_ref()); - let stream = self - .engine - .dispatch_with_tokenizer(&placement, &mut payload, &resp_ctx.tokenizer) - .await - .map_err(engine_err_to_response)?; + let (mut payload, mut resp_ctx) = + prepare::prepare_chat(req, headers, model_id, &components)?; + let (_guards, stream) = self.dispatch(&mut payload, &mut resp_ctx).await?; render::chat_aggregator::process_typed(stream, resp_ctx).await } + /// Plan the request, read its output as its producer's, and dispatch it: the loads + /// held until the response ends, and its stream, whose cached tokens are reconciled + /// with the estimate the plan's selection made on the worker computing the prompt. + async fn dispatch( + &self, + payload: &mut GenerationPayload, + ctx: &mut ResponseContext, + ) -> Result<(Vec, TokenHandle), Response> { + let (dispatched, estimate) = route_trace::estimated(async { + let placement = self.plan_for(payload, ctx).await?; + self.read_as_atom(&placement, ctx); + let guards = self.load_guards(&placement, ctx.headers.as_ref()); + let stream = self + .engine + .dispatch_with_tokenizer(&placement, payload, &ctx.tokenizer) + .await + .map_err(engine_err_to_response)?; + Ok::<_, Response>((placement, guards, stream)) + }) + .await; + let (placement, guards, stream) = dispatched?; + // A pair's cached tokens are the ones its prefill reused. + let pool = match placement { + PlacementPlan::Single { .. } => metrics_labels::WORKER_REGULAR, + PlacementPlan::Pair { .. } => metrics_labels::WORKER_PREFILL, + }; + let reconciled = Reconciled { + inner: stream, + pool, + estimate, + done: false, + }; + Ok((guards, TokenHandle::new(reconciled))) + } + /// The loads held until the response ends; none when dispatch holds them. fn load_guards( &self, @@ -405,6 +462,45 @@ impl Pipeline { } } +/// A stream that records its first Complete's cached prompt tokens against `pool`, and +/// against the router's `estimate` of them, as the HTTP routers reconcile a response's usage. +struct Reconciled { + inner: TokenHandle, + pool: &'static str, + estimate: Option, + done: bool, +} + +impl Stream for Reconciled { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let item = ready!(Pin::new(&mut self.inner).poll_next(cx)); + if let Some(Ok(TokenChunk::Complete { usage, meta, .. })) = &item { + // n siblings share one prompt, as their first reports it. + if !std::mem::replace(&mut self.done, true) { + let (prompt, cached) = (usage.prompt_tokens.into(), meta.cached_tokens.into()); + MeshMetrics::record_route_cache_tokens(self.pool, prompt, cached); + if let Some(ratio) = self.estimate { + let estimated = (ratio * prompt as f64).round() as u64; + MeshMetrics::record_route_cache_estimate(self.pool, prompt, estimated, cached); + } + } + } + Poll::Ready(item) + } +} + +impl TokenSource for Reconciled { + fn mark_completed(&mut self) { + self.inner.mark_completed(); + } + + fn clock(&self) -> Option { + self.inner.clock() + } +} + fn make_load_guards(plan: &PlacementPlan, headers: Option<&HeaderMap>) -> Vec { match plan { PlacementPlan::Single { worker, .. } => { @@ -462,11 +558,14 @@ fn engine_err_to_response(err: EngineError) -> Response { mod atom_output_tests { use super::*; use crate::{ + core::BasicWorkerBuilder, protocols::generate::GenerateRequest, routers::test_mocks::{ dispatcher::MockDispatcher, planner::MockPdPlanner, tokenizer::byte_level_tokenizer_dir, }, - tokenizer::{huggingface::HuggingFaceTokenizer, stop::SequenceDecoderOutput}, + tokenizer::{ + huggingface::HuggingFaceTokenizer, stop::SequenceDecoderOutput, traits::Tokenizer, + }, }; /// A `/generate` of `body`, prepared as the router prepares it: its own @@ -478,7 +577,7 @@ mod atom_output_tests { tokenizer, params.and_then(|p| p.stop.as_ref()), None, - true, + params.and_then(|p| p.skip_special_tokens).unwrap_or(true), false, ); ResponseContext { @@ -495,7 +594,9 @@ mod atom_output_tests { reasoning_parser_factory: None, configured_tool_parser: None, configured_reasoning_parser: None, - prompt_opener: None, + prompt_opener: Some("".to_string()), + reads_as_atom: false, + usage_on_finish: false, } } @@ -516,36 +617,237 @@ mod atom_output_tests { text } - #[test] - fn atom_output_keeps_the_text_past_a_stop_and_hides_the_end_of_sequence() { - let dir = byte_level_tokenizer_dir(&[], false, serde_json::json!({})); - let path = dir.path().join("tokenizer.json"); - let tokenizer: Arc = - Arc::new(HuggingFaceTokenizer::from_file(path.to_str().unwrap()).unwrap()); - // "", the second token added after the 256 bytes, ends the output. - let eos = 257; - let ids: Vec = "ab. c".bytes().map(u32::from).collect(); - let output = [ids.as_slice(), &[eos]].concat(); - let pipeline = Pipeline::with_injected( + fn pipeline() -> Pipeline { + Pipeline::with_injected( Arc::new(MockPdPlanner::new(vec![])), Arc::new(MockDispatcher::new(vec![])), "regular", - ); + ) + } - let mut ctx = generate_ctx( - &tokenizer, - r#"{"text": "hi", "sampling_params": {"stop": ["."]}}"#, - ); - // The router's own reading cuts at the stop. + fn single(runtime: RuntimeType, labels: &[(&str, &str)]) -> PlacementPlan { + let mut builder = BasicWorkerBuilder::new("grpc://w:1").runtime_type(runtime); + for (key, value) in labels { + builder = builder.label(*key, *value); + } + PlacementPlan::Single { + worker: Arc::new(builder.build()), + policy_name: "random", + prefill_tokens: 0, + } + } + + fn byte_level() -> Arc { + let dir = byte_level_tokenizer_dir(&[], false, serde_json::json!({})); + let path = dir.path().join("tokenizer.json"); + Arc::new(HuggingFaceTokenizer::from_file(path.to_str().unwrap()).unwrap()) + } + + // "", an added token that is not special, ends the output: only the end + // ids' hiding keeps it out. + const EOS: u32 = 260; + // "", a special token. + const SPECIAL: u32 = 257; + const STOPPED_AT_DOT: &str = + r#"{"text": "hi", "sampling_params": {"stop": ["."], "skip_special_tokens": false}}"#; + + fn output() -> Vec { + let ids: Vec = "ab. c".bytes().map(u32::from).collect(); + [ids.as_slice(), &[EOS]].concat() + } + + #[test] + fn atom_output_keeps_the_text_past_a_stop_and_hides_the_end_of_sequence() { + let tokenizer = byte_level(); + let output = output(); + let plan = single(RuntimeType::Sglang, &[]); + + let mut ctx = generate_ctx(&tokenizer, STOPPED_AT_DOT); + pipeline().read_as_atom(&plan, &mut ctx); + // The router's own reading cuts at the stop, and keeps no opener. assert_eq!(decode(&mut ctx.stop_decoder, &output), "ab"); + assert_eq!(ctx.prompt_opener, None); + assert!(!ctx.reads_as_atom); - let atom = pipeline.reading_output_as_atom(AtomOutput::new(vec![eos])); - let mut ctx = generate_ctx( - &tokenizer, - r#"{"text": "hi", "sampling_params": {"stop": ["."]}}"#, - ); - atom.read_as_atom(&mut ctx); + let atom = pipeline().reading_output_as_atom(AtomOutput::new(vec![EOS])); + let mut ctx = generate_ctx(&tokenizer, STOPPED_AT_DOT); + atom.read_as_atom(&plan, &mut ctx); // The engine stopped where the stop's ids matched; the text is all of it. assert_eq!(decode(&mut ctx.stop_decoder, &output), "ab. c"); + assert_eq!(ctx.prompt_opener.as_deref(), Some("")); + assert!(ctx.reads_as_atom); + } + + #[test] + fn an_atom_reading_skips_special_tokens_as_atom_s_http_routes_do() { + // Both requests ask for special tokens kept; ATOM's HTTP routes skip them. + let tokenizer = byte_level(); + let output = [u32::from(b'a'), SPECIAL, u32::from(b'b')]; + let chat = || { + let mut ctx = chat_ctx(&tokenizer, "m", None); + let req = ChatCompletionRequest { + skip_special_tokens: false, + ..Default::default() + }; + ctx.original = ProtocolRequest::Chat(Arc::new(req)); + ctx.stop_decoder = create_stop_decoder(&tokenizer, None, None, false, false); + ctx + }; + let generate = || generate_ctx(&tokenizer, STOPPED_AT_DOT); + for request in [&chat as &dyn Fn() -> ResponseContext, &generate] { + let mut ctx = request(); + pipeline().read_as_atom(&single(RuntimeType::Sglang, &[]), &mut ctx); + assert_eq!(decode(&mut ctx.stop_decoder, &output), "ab"); + let mut ctx = request(); + pipeline().read_as_atom(&single(RuntimeType::Atom, &[]), &mut ctx); + assert_eq!(decode(&mut ctx.stop_decoder, &output), "ab"); + } + } + + #[test] + fn an_atom_producer_is_read_with_the_end_ids_its_worker_lists() { + let tokenizer = byte_level(); + let output = output(); + let eos = EOS.to_string(); + let listed = format!("[{eos}]"); + let atom = single(RuntimeType::Atom, &[(EOS_TOKEN_IDS_LABEL, &listed)]); + + let mut ctx = generate_ctx(&tokenizer, STOPPED_AT_DOT); + pipeline().read_as_atom(&atom, &mut ctx); + assert_eq!(decode(&mut ctx.stop_decoder, &output), "ab. c"); + assert_eq!(ctx.prompt_opener.as_deref(), Some("")); + + // ignore_eos runs past the end ids, so they stay in the text. + let body = r#"{"text": "hi", "sampling_params": {"ignore_eos": true, "skip_special_tokens": false}}"#; + let mut ctx = generate_ctx(&tokenizer, body); + pipeline().read_as_atom(&atom, &mut ctx); + assert_eq!(decode(&mut ctx.stop_decoder, &output), "ab. c"); + + // A pair's output is its decode worker's. + let PlacementPlan::Single { worker, .. } = atom else { + unreachable!() + }; + let PlacementPlan::Single { + worker: prefill, .. + } = single(RuntimeType::Sglang, &[]) + else { + unreachable!() + }; + let pair = PlacementPlan::Pair { + prefill, + decode: worker, + prefill_policy: "random", + decode_policy: "random", + prefill_tokens: 0, + }; + let mut ctx = generate_ctx(&tokenizer, STOPPED_AT_DOT); + pipeline().read_as_atom(&pair, &mut ctx); + assert_eq!(decode(&mut ctx.stop_decoder, &output), "ab. c"); + } + + #[test] + fn an_atom_producer_places_streamed_usage_as_its_worker_says() { + let tokenizer = byte_level(); + for (labels, usage_on_finish) in [ + (&[(USAGE_ON_FINISH_LABEL, "true")][..], true), + (&[][..], false), + ] { + let mut ctx = generate_ctx(&tokenizer, STOPPED_AT_DOT); + pipeline().read_as_atom(&single(RuntimeType::Atom, labels), &mut ctx); + assert_eq!(ctx.usage_on_finish, usage_on_finish); + } + } + + /// A chat to `model` whose reply is read with the router's `configured` parser. + fn chat_ctx( + tokenizer: &Arc, + model: &str, + configured: Option<&str>, + ) -> ResponseContext { + let req = ChatCompletionRequest { + model: model.to_string(), + separate_reasoning: true, + ..Default::default() + }; + ResponseContext { + original: ProtocolRequest::Chat(Arc::new(req)), + model_id: Some(model.to_string()), + headers: None, + original_text: None, + processed_messages: None, + tokenizer: Arc::clone(tokenizer), + stop_decoder: create_stop_decoder(tokenizer, None, None, true, false), + request_id: "chat-1".to_string(), + created: 0, + tool_parser_factory: Some(crate::tool_parser::ParserFactory::new()), + reasoning_parser_factory: Some(reasoning_parser::ParserFactory::new()), + configured_tool_parser: None, + configured_reasoning_parser: configured.map(str::to_string), + prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, + } + } + + #[tokio::test] + async fn an_atom_reply_is_parsed_by_its_worker_s_parsers_under_any_model_name() { + use crate::routers::{ + render::chat_aggregator, + token_handle::test_support::synthetic_single_stream, + token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}, + }; + let tokenizer = byte_level(); + let reply = tokenizer + .encode("plananswer", false) + .unwrap(); + let answer = |ctx: ResponseContext| { + let complete = TokenChunk::Complete { + token_ids: reply.token_ids().to_vec(), + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage::default(), + logprobs: None, + input_logprobs: None, + meta: WorkerMeta::default(), + }; + let stream = synthetic_single_stream(vec![Ok(complete)]); + async move { + let resp = chat_aggregator::process_typed(stream, ctx).await.unwrap(); + let message = &resp.choices[0].message; + (message.reasoning_content.clone(), message.content.clone()) + } + }; + let worker = BasicWorkerBuilder::new("grpc://w:1") + .runtime_type(RuntimeType::Atom) + .reasoning_parser("qwen3") + .build(); + let plan = PlacementPlan::Single { + worker: Arc::new(worker), + policy_name: "random", + prefill_tokens: 0, + }; + + // Served under an alias that names no parser, the worker's splits the reply. + let mut ctx = chat_ctx(&tokenizer, "served-alias", None); + pipeline().read_as_atom(&plan, &mut ctx); + assert_eq!(ctx.configured_reasoning_parser.as_deref(), Some("qwen3")); + let split = (Some("plan".to_string()), Some("answer".to_string())); + assert_eq!(answer(ctx).await, split); + + // The router's own parser wins. + let mut ctx = chat_ctx(&tokenizer, "served-alias", Some("deepseek_r1")); + pipeline().read_as_atom(&plan, &mut ctx); + assert_eq!( + ctx.configured_reasoning_parser.as_deref(), + Some("deepseek_r1") + ); + + // Another runtime's worker leaves the model name to choose. + let sglang = single(RuntimeType::Sglang, &[]); + let mut ctx = chat_ctx(&tokenizer, "served-alias", None); + pipeline().read_as_atom(&sglang, &mut ctx); + assert_eq!(ctx.configured_reasoning_parser, None); + let unsplit = (None, Some("plananswer".to_string())); + assert_eq!(answer(ctx).await, unsplit); } } diff --git a/atom/mesh/src/routers/grpc/router.rs b/atom/mesh/src/routers/grpc/router.rs index f1812ffaf9d..18c70de4aa5 100644 --- a/atom/mesh/src/routers/grpc/router.rs +++ b/atom/mesh/src/routers/grpc/router.rs @@ -8,7 +8,7 @@ use tracing::debug; use super::{ completion_adapter::{ - completion_to_generate, wrap_generate_response_as_completion, + completion_to_generate, without_logprobs, wrap_generate_response_as_completion, wrap_streaming_generate_as_completion, }, pipeline::Pipeline, @@ -16,7 +16,7 @@ use super::{ use crate::{ app_context::AppContext, config::types::RetryConfig, - core::{is_retryable_status, RetryExecutor, WorkerRegistry, UNKNOWN_MODEL_ID}, + core::{is_retryable_status, RetryExecutor, RuntimeType, WorkerRegistry, UNKNOWN_MODEL_ID}, observability::metrics::{metrics_labels, MeshMetrics}, protocols::{ chat::ChatCompletionRequest, completion::CompletionRequest, generate::GenerateRequest, @@ -29,7 +29,8 @@ use crate::{ handlers as responses_handlers, retrieve::{cancel_response_impl, get_response_impl}, }, - prepare, RouterTrait, SentChatBody, + prepare::{self, inference::ParsedInference}, + RouterTrait, SentChatBody, }, }; @@ -51,25 +52,28 @@ impl GrpcRouter { return Err("gRPC router requires tool parser factory".to_string()); } - let worker_registry = ctx.worker_registry.clone(); - let pipeline = Pipeline::new_regular(worker_registry.clone(), ctx.policy_registry.clone()); - let app_context = ctx.clone(); + let pipeline = + Pipeline::new_regular(ctx.worker_registry.clone(), ctx.policy_registry.clone()); + Ok(Self::with_pipeline(ctx, pipeline)) + } + /// The router over `pipeline`; `new` gives it the pipeline over `ctx`'s registries. + pub(super) fn with_pipeline(ctx: &Arc, pipeline: Pipeline) -> Self { let responses_context = ResponsesContext::new( Arc::new(pipeline.clone()), - app_context.clone(), + ctx.clone(), ctx.response_storage.clone(), ctx.conversation_storage.clone(), ctx.conversation_item_storage.clone(), ); - Ok(GrpcRouter { - worker_registry, + GrpcRouter { + worker_registry: ctx.worker_registry.clone(), pipeline, - app_context, + app_context: ctx.clone(), responses_context, retry_config: ctx.router_config.effective_retry_config(), - }) + } } /// Route a chat, its prompt rendered from its body as `sent` where the @@ -189,6 +193,49 @@ impl GrpcRouter { } } +/// Whether `model_id` has an ATOM gRPC worker; those serve neither media nor Responses. +pub(super) fn atom_serves(workers: &WorkerRegistry, model_id: Option<&str>) -> bool { + model_id.is_some_and(|model| { + let workers = workers.get_by_model(model); + workers + .iter() + .any(|worker| worker.metadata().runtime_type == RuntimeType::Atom) + }) +} + +/// Why an ATOM gRPC worker of `model_id` cannot serve the chat `body`, if it cannot. +pub(super) fn atom_chat_refusal( + workers: &WorkerRegistry, + body: &ChatCompletionRequest, + model_id: Option<&str>, +) -> Option { + if !atom_serves(workers, model_id) { + return None; + } + if ParsedInference::chat_carries_media(body) { + return Some(media_refused()); + } + // top_logprobs needs logprobs + body.logprobs.then(logprobs_refused) +} + +/// ATOM gRPC workers take token ids alone, so a request's media would be dropped. +pub(super) fn media_refused() -> Response { + error::bad_request( + "unsupported_media", + "ATOM gRPC workers serve no image, video, audio or embedding input", + ) +} + +/// ATOM gRPC workers return no logprobs yet; /v1/completions keeps its null, as +/// ATOM's HTTP route answers it. +pub(super) fn logprobs_refused() -> Response { + error::bad_request( + "unsupported_logprobs", + "ATOM gRPC workers return no logprobs", + ) +} + impl std::fmt::Debug for GrpcRouter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let stats = self.worker_registry.stats(); @@ -210,6 +257,14 @@ impl RouterTrait for GrpcRouter { body: &GenerateRequest, model_id: Option<&str>, ) -> Response { + if atom_serves(&self.worker_registry, model_id) { + if ParsedInference::generate_carries_media(body) { + return media_refused(); + } + if body.return_logprob == Some(true) { + return logprobs_refused(); + } + } self.route_generate_impl(headers, body, model_id).await } @@ -228,6 +283,9 @@ impl RouterTrait for GrpcRouter { sent: Option, model_id: Option<&str>, ) -> Response { + if let Some(refused) = atom_chat_refusal(&self.worker_registry, body, model_id) { + return refused; + } self.route_chat_impl(headers, body, model_id, sent).await } @@ -237,6 +295,9 @@ impl RouterTrait for GrpcRouter { body: &ChatCompletionRequest, model_id: Option<&str>, ) -> Response { + if let Some(refused) = atom_chat_refusal(&self.worker_registry, body, model_id) { + return refused; + } self.route_chat_impl(headers, body, model_id, None).await } @@ -247,6 +308,7 @@ impl RouterTrait for GrpcRouter { model_id: Option<&str>, ) -> Response { let synthetic = match completion_to_generate(body) { + Ok(g) if atom_serves(&self.worker_registry, model_id) => without_logprobs(g), Ok(g) => g, Err(msg) => return error::bad_request("completion_unsupported_field", msg), }; @@ -275,6 +337,12 @@ impl RouterTrait for GrpcRouter { body: &ResponsesRequest, model_id: Option<&str>, ) -> Response { + if atom_serves(&self.worker_registry, model_id) { + return error::not_implemented( + "unsupported_api", + "Responses requires an HTTP backend for ATOM workers", + ); + } self.route_responses_impl(headers, body, model_id).await } diff --git a/atom/mesh/src/routers/grpc/tests.rs b/atom/mesh/src/routers/grpc/tests.rs index bebd76c7732..6485ca939ac 100644 --- a/atom/mesh/src/routers/grpc/tests.rs +++ b/atom/mesh/src/routers/grpc/tests.rs @@ -864,6 +864,15 @@ mod h_completion_adapter { completion_to_generate, wrap_generate_response_as_completion, wrap_streaming_generate_as_completion, }; + use crate::routers::prepare::response_context::{ProtocolRequest, ResponseContext}; + use crate::routers::prepare::stop_decoder_builder::create_stop_decoder; + use crate::routers::render::generate_aggregator; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{ + FinishReason, SeqTiming, TokenChunk, Usage, WorkerMeta, + }; + use crate::tokenizer::{traits::Tokenizer, MockTokenizer}; + use std::sync::Arc; fn minimal_completion_request() -> CompletionRequest { serde_json::from_value(json!({ @@ -1629,4 +1638,540 @@ mod h_completion_adapter { let total = usage["total_tokens"].as_u64().unwrap(); assert_eq!(total, prompt + compl); } + + /// The `/generate` body the aggregator answers `completes` with, as an upstream response. + async fn generated(completes: Vec) -> Response { + let tokenizer: Arc = Arc::new(MockTokenizer::new()); + let req: crate::protocols::generate::GenerateRequest = + serde_json::from_str(r#"{"text": "hi"}"#).unwrap(); + let ctx = ResponseContext { + original: ProtocolRequest::Generate(Arc::new(req)), + model_id: Some("m".to_string()), + headers: None, + original_text: Some("hi".to_string()), + processed_messages: None, + stop_decoder: create_stop_decoder(&tokenizer, None, None, true, false), + tokenizer, + request_id: "cmpl-1".to_string(), + created: 0, + tool_parser_factory: None, + reasoning_parser_factory: None, + configured_tool_parser: None, + configured_reasoning_parser: None, + prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, + }; + let stream = synthetic_single_stream(completes.into_iter().map(Ok).collect()); + generate_aggregator::process(stream, ctx).await + } + + fn sibling(timing: Option) -> TokenChunk { + TokenChunk::Complete { + token_ids: vec![1], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 3, + completion_tokens: 1, + total_tokens: 4, + }, + logprobs: None, + input_logprobs: None, + meta: WorkerMeta { + cached_tokens: 2, + timing, + ..Default::default() + }, + } + } + + async fn completion_usage(completes: Vec) -> Value { + let upstream = generated(completes).await; + let resp = wrap_generate_response_as_completion(upstream, "m".into()).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + serde_json::from_slice::(&body).unwrap()["usage"].clone() + } + + #[tokio::test] + async fn an_atom_completion_reports_its_timing_once_per_request() { + let timed = |ttft_s, latency_s| { + Some(SeqTiming { + ttft: ttft_s, + tpot: 0.01, + latency: latency_s, + }) + }; + let usage = completion_usage(vec![sibling(timed(0.1, 1.0))]).await; + let expected = json!({ + "prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4, + "ttft_s": 0.1, "tpot_s": 0.01, "latency_s": 1.0, + }); + assert_eq!(usage, expected); + + // n=2: the prompt once, the slowest sibling's timing, and n. + let usage = + completion_usage(vec![sibling(timed(0.1, 2.0)), sibling(timed(0.3, 1.0))]).await; + let expected = json!({ + "prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5, + "ttft_s": 0.3, "tpot_s": 0.01, "latency_s": 2.0, "num_choices": 2, + }); + assert_eq!(usage, expected); + + // An SGLang or vLLM completion keeps its usage. + let usage = completion_usage(vec![sibling(None)]).await; + let expected = json!({"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4}); + assert_eq!(usage, expected); + } +} + +mod i_atom_refusals { + use std::sync::Arc; + + use axum::http::StatusCode; + use http::{header::CONTENT_TYPE, HeaderMap, HeaderValue}; + use serde_json::{json, Value}; + + use crate::app_context::AppContext; + use crate::config::RouterConfig; + use crate::core::placement::types::PlacementPlan; + use crate::core::prepare_pool::PreparePoolRuntime; + use crate::core::{BasicWorkerBuilder, ConnectionMode, RuntimeType, Worker, WorkerType}; + use crate::observability::metrics::metrics_labels; + use crate::routers::comm::error::extract_error_code_from_response; + use crate::routers::grpc::engine::{atom::request::generate_request, Dispatcher}; + use crate::routers::grpc::{pd_router::GrpcPDRouter, pipeline::Pipeline, router::GrpcRouter}; + use crate::routers::ingress::InferenceEnvelope; + use crate::routers::prepare::generation_payload::GenerationPayload; + use crate::routers::test_mocks::{self, hf_tokenizer, MockDispatcher, MockPdPlanner}; + use crate::routers::token_handle::engine_error::EngineError; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}; + use crate::routers::token_handle::token_handle::TokenHandle; + use crate::routers::RouterTrait; + use crate::tokenizer::registry::TokenizerRegistry; + use crate::tokenizer::traits::Tokenizer; + + type Answer = (StatusCode, &'static str); // a status and its error code + const SERVED: Answer = (StatusCode::OK, ""); + const MEDIA: Answer = (StatusCode::BAD_REQUEST, "unsupported_media"); + const LOGPROBS: Answer = (StatusCode::BAD_REQUEST, "unsupported_logprobs"); + const UNSUPPORTED: Answer = (StatusCode::NOT_IMPLEMENTED, "unsupported_api"); + const MESSAGE_TOOLS: Answer = (StatusCode::BAD_REQUEST, "invalid_message_tools"); + + fn owned((status, code): Answer) -> (StatusCode, String) { + (status, code.to_owned()) + } + + /// Each request to model "m", and the answer when ATOM gRPC workers serve "m". + fn requests() -> Vec<(&'static str, Value, Answer)> { + let text = json!({"type": "text", "text": "test"}); + let image = json!({"type": "image_url", "image_url": {"url": "https://x/a.png"}}); + let video = json!({"type": "video_url", "video_url": {"url": "https://x/a.mp4"}}); + let chat = |parts: Vec<&Value>| { + let message = json!({"role": "user", "content": parts}); + json!({"model": "m", "messages": [message]}) + }; + let generate = |media: Option<&str>| { + let mut body = json!({"model": "m", "text": "test"}); + if let Some(field) = media { + body[field] = json!("https://x/a"); + } + body + }; + let mut chat_logprobs = chat(vec![&text]); + chat_logprobs["logprobs"] = json!(true); + chat_logprobs["top_logprobs"] = json!(2); + let mut generate_logprobs = generate(None); + generate_logprobs["return_logprob"] = json!(true); + // ATOM's HTTP /v1/completions answers logprobs null; so does this route, past + // ATOM's request builder, which refuses logprobs. + let completion_logprobs = json!({"model": "m", "prompt": "test", "logprobs": 1}); + // The typed request drops a system message's tools; ATOM reads them from the body. + let system = json!({"role": "system", "content": "test", "tools": "not a list"}); + let message_tools = json!({"model": "m", "messages": [system]}); + let responses = json!({"model": "m", "input": "test"}); + let message = json!({"role": "user", "content": "test"}); + let messages = json!({"model": "m", "max_tokens": 8, "messages": [message]}); + vec![ + ("/v1/chat/completions", chat(vec![&text]), SERVED), + ("/v1/chat/completions", chat(vec![&text, &image]), MEDIA), + ("/v1/chat/completions", chat(vec![&text, &video]), MEDIA), + ("/v1/chat/completions", chat_logprobs, LOGPROBS), + ("/v1/chat/completions", message_tools, MESSAGE_TOOLS), + ("/generate", generate(None), SERVED), + ("/generate", generate(Some("image_data")), MEDIA), + ("/generate", generate(Some("video_data")), MEDIA), + ("/generate", generate(Some("audio_data")), MEDIA), + ("/generate", generate_logprobs, LOGPROBS), + ("/v1/completions", completion_logprobs, SERVED), + ("/v1/responses", responses, UNSUPPORTED), + ("/v1/messages", messages, UNSUPPORTED), + ] + } + + fn completed() -> Result { + Ok(synthetic_single_stream(vec![Ok(TokenChunk::Complete { + token_ids: vec![0], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 1, + completion_tokens: 1, + total_tokens: 2, + }, + logprobs: None, + input_logprobs: None, + meta: WorkerMeta { + request_id: "req".to_string(), + weight_version: None, + cached_tokens: 0, + timing: None, + }, + })])) + } + + fn worker(model: &str, runtime: RuntimeType, kind: WorkerType) -> Arc { + let worker = BasicWorkerBuilder::new(format!("grpc://{model}-{kind}:1")) + .worker_type(kind) + .connection_mode(ConnectionMode::Grpc { port: None }) + .runtime_type(runtime) + .model_id(model) + // An ATOM worker reporting none has its chats refused. + .label("chat_template", "{{ messages }}") + .build(); + Arc::new(worker) + } + + /// `MockDispatcher`'s answer to what ATOM's request builder accepts for an ATOM worker. + struct AtomBuilding(Arc); + + #[async_trait::async_trait] + impl Dispatcher for AtomBuilding { + async fn dispatch( + &self, + placement: &PlacementPlan, + payload: &mut GenerationPayload, + ) -> Result { + self.0.dispatch(placement, payload).await + } + + async fn dispatch_with_tokenizer( + &self, + placement: &PlacementPlan, + payload: &mut GenerationPayload, + tokenizer: &Arc, + ) -> Result { + if let PlacementPlan::Single { worker, .. } = placement { + if worker.metadata().runtime_type == RuntimeType::Atom { + generate_request(payload, worker.as_ref(), Some(tokenizer.as_ref()))?; + } + } + self.0.dispatch(placement, payload).await + } + } + + /// Each request's status and error code through `route_inference` when one `runtime` + /// worker serves "m" beside an ATOM worker of model "a", and how many were dispatched. + async fn answers(runtime: RuntimeType) -> (Vec<(StatusCode, String)>, usize) { + let config = RouterConfig::default(); + let pool = PreparePoolRuntime::new(config.resolved_prepare_pool().unwrap()).unwrap(); + let ctx = Arc::new( + AppContext::from_config(config, 5, pool.handle()) + .await + .unwrap(), + ); + let id = TokenizerRegistry::generate_id(); + ctx.tokenizer_registry + .load(&id, "m", "hf-test", || async { Ok(hf_tokenizer()) }) + .await + .unwrap(); + ctx.tokenizer_inline_templates + .write() + .insert(id, "{{ messages }}".into()); + let served = worker("m", runtime, WorkerType::Regular); + ctx.worker_registry.register(served.clone()); + ctx.worker_registry + .register(worker("a", RuntimeType::Atom, WorkerType::Regular)); + let dispatcher = Arc::new(MockDispatcher::repeat_with_stream(completed)); + let planner = Arc::new(MockPdPlanner::repeat_single(served, "random")); + let building = Arc::new(AtomBuilding(dispatcher.clone())); + let pipeline = Pipeline::with_injected(planner, building, metrics_labels::BACKEND_REGULAR); + let router = GrpcRouter::with_pipeline(&ctx, pipeline); + + let mut answers = Vec::new(); + for (path, body, _) in requests() { + let mut headers = HeaderMap::new(); + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + let body = body.to_string().into(); + let request = InferenceEnvelope::parse(path.parse().unwrap(), headers, body, &ctx) + .await + .unwrap(); + let response = router.route_inference(request, &ctx).await; + let code = extract_error_code_from_response(&response).to_owned(); + answers.push((response.status(), code)); + } + (answers, dispatcher.calls().len()) + } + + #[tokio::test] + async fn test_atom_workers_get_no_media_logprobs_responses_or_messages_request() { + let (answers, dispatched) = answers(RuntimeType::Atom).await; + let expected: Vec<_> = requests().into_iter().map(|(_, _, a)| owned(a)).collect(); + assert_eq!(answers, expected); + assert_eq!( + dispatched, 3, + "the text chat, the text generate and the completion" + ); + } + + #[tokio::test] + async fn test_sglang_and_vllm_workers_keep_serving_media_logprobs_and_responses() { + for runtime in [RuntimeType::Sglang, RuntimeType::Vllm] { + let (answers, dispatched) = answers(runtime.clone()).await; + let expected: Vec<_> = requests() + .into_iter() + .map(|(path, _, _)| match path { + "/v1/messages" => owned(UNSUPPORTED), + _ => owned(SERVED), + }) + .collect(); + assert_eq!(answers, expected, "{runtime}"); + assert_eq!(dispatched, expected.len() - 1, "{runtime}"); + } + } + + #[tokio::test] + async fn test_an_atom_pair_gets_no_media_or_logprobs_request() { + let ctx = test_mocks::app_context_with_hf_tokenizer("m"); + let router = GrpcPDRouter::new(&ctx).await.unwrap(); + let prefill = WorkerType::Prefill { + bootstrap_port: None, + }; + for kind in [prefill, WorkerType::Decode] { + ctx.worker_registry + .register(worker("m", RuntimeType::Atom, kind)); + } + let refused = |answer: &Answer| *answer == MEDIA || *answer == LOGPROBS; + for (path, body, answer) in requests().into_iter().filter(|(_, _, a)| refused(a)) { + let response = match path { + "/generate" => { + let body = serde_json::from_value(body).unwrap(); + router.route_generate(None, &body, Some("m")).await + } + _ => { + let body = serde_json::from_value(body).unwrap(); + router.route_chat(None, &body, Some("m")).await + } + }; + let code = extract_error_code_from_response(&response); + assert_eq!((response.status(), code), answer, "{path}"); + } + } +} + +mod j_atom_stops { + use std::sync::Arc; + + use axum::body::to_bytes; + use serde_json::{json, Value}; + + use crate::core::{BasicWorkerBuilder, ConnectionMode, RuntimeType, WorkerType}; + use crate::observability::metrics::metrics_labels; + use crate::routers::grpc::pipeline::Pipeline; + use crate::routers::test_mocks::{self, MockDispatcher, MockPdPlanner}; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}; + + /// The text `/generate` answers when a `runtime` worker returns "test test test" + /// for a request whose stop string is "test". + async fn text(runtime: RuntimeType) -> String { + let worker = BasicWorkerBuilder::new("grpc://w:1") + .worker_type(WorkerType::Regular) + .connection_mode(ConnectionMode::Grpc { port: None }) + .runtime_type(runtime) + .model_id("m") + .build(); + let output = || { + Ok(synthetic_single_stream(vec![Ok(TokenChunk::Complete { + token_ids: vec![0, 0, 0], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 1, + completion_tokens: 3, + total_tokens: 4, + }, + logprobs: None, + input_logprobs: None, + meta: WorkerMeta { + request_id: "req".to_string(), + weight_version: None, + cached_tokens: 0, + timing: None, + }, + })])) + }; + let pipeline = Pipeline::with_injected( + Arc::new(MockPdPlanner::repeat_single(Arc::new(worker), "random")), + Arc::new(MockDispatcher::repeat_with_stream(output)), + metrics_labels::BACKEND_REGULAR, + ); + let body = json!({"model": "m", "text": "test", "sampling_params": {"stop": ["test"]}}); + let request = Arc::new(serde_json::from_value(body).unwrap()); + let ctx = test_mocks::app_context_with_hf_tokenizer("m"); + let response = pipeline + .execute_generate(request, None, Some("m".to_string()), ctx) + .await; + let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap(); + let answer: Value = serde_json::from_slice(&body).unwrap(); + let answer = if answer.is_array() { + &answer[0] + } else { + &answer + }; + answer["text"].as_str().unwrap().to_string() + } + + #[tokio::test] + async fn test_an_atom_output_keeps_what_atom_returned_past_a_stop_string() { + assert_eq!(text(RuntimeType::Atom).await, "test test test"); + } + + #[tokio::test] + async fn test_an_sglang_output_is_still_cut_at_its_stop_string() { + let sglang = text(RuntimeType::Sglang).await; + assert!(!sglang.contains("test"), "{sglang:?}"); + } +} + +mod k_cache_reconcile { + use std::sync::Arc; + + use async_trait::async_trait; + + use crate::core::placement::traits::PdPlanner; + use crate::core::placement::types::{PlacementError, PlacementPlan, RequestDescriptor}; + use crate::core::WorkerType; + use crate::observability::{metrics::metrics_labels, route_trace}; + use crate::protocols::generate::GenerateRequest; + use crate::routers::grpc::pipeline::Pipeline; + use crate::routers::test_mocks::{self, mock_grpc_worker, MockDispatcher}; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}; + + /// Plans one regular worker, or a pair, and expects half the prompt cached on the + /// worker that computes it, as a cache-aware policy's selection records. + struct EstimatingPlanner { + pair: bool, + } + + #[async_trait] + impl PdPlanner for EstimatingPlanner { + async fn plan(&self, _: &RequestDescriptor<'_>) -> Result { + if !self.pair { + let worker = mock_grpc_worker("grpc://w:1", WorkerType::Regular); + route_trace::record_estimate( + metrics_labels::WORKER_REGULAR, + Some(&worker), + Some(0.5), + ); + return Ok(PlacementPlan::Single { + worker, + policy_name: "cache_aware", + prefill_tokens: 0, + }); + } + let prefill = mock_grpc_worker( + "grpc://p:1", + WorkerType::Prefill { + bootstrap_port: None, + }, + ); + let decode = mock_grpc_worker("grpc://d:1", WorkerType::Decode); + route_trace::record_estimate(metrics_labels::WORKER_PREFILL, Some(&prefill), Some(0.5)); + route_trace::record_estimate(metrics_labels::WORKER_DECODE, Some(&decode), Some(0.9)); + Ok(PlacementPlan::Pair { + prefill, + decode, + prefill_policy: "cache_aware", + decode_policy: "cache_aware", + prefill_tokens: 0, + }) + } + } + + fn completed() -> TokenChunk { + TokenChunk::Complete { + token_ids: vec![1], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 100, + completion_tokens: 1, + total_tokens: 101, + }, + logprobs: None, + input_logprobs: None, + meta: WorkerMeta { + cached_tokens: 40, + ..Default::default() + }, + } + } + + /// The metrics a unary /generate placed by `planner` renders. + async fn rendered(pair: bool) -> String { + let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder(); + let handle = recorder.handle(); + let _recorder = metrics::set_default_local_recorder(&recorder); + let dispatcher = MockDispatcher::repeat_with_stream(|| { + // n=2: the siblings' one prompt is reconciled once. + Ok(synthetic_single_stream(vec![ + Ok(completed()), + Ok(completed()), + ])) + }); + let pipeline = Pipeline::with_injected( + Arc::new(EstimatingPlanner { pair }), + Arc::new(dispatcher), + metrics_labels::BACKEND_REGULAR, + ); + let registry = test_mocks::tokenizer_registry_with("m"); + let ctx = test_mocks::app_context_with_tokenizer_registry(registry); + let req: GenerateRequest = serde_json::from_str(r#"{"text": "test"}"#).unwrap(); + let response = pipeline + .execute_generate(Arc::new(req), None, Some("m".to_string()), ctx) + .await; + assert!(response.status().is_success()); + axum::body::to_bytes(response.into_body(), 64 * 1024) + .await + .unwrap(); + handle.render() + } + + fn assert_reconciled(rendered: &str, pool: &str) { + for line in [ + format!(r#"mesh_route_cache_tokens_total{{pool="{pool}",kind="prompt"}} 100"#), + format!(r#"mesh_route_cache_tokens_total{{pool="{pool}",kind="cached"}} 40"#), + format!( + r#"mesh_route_cache_estimate_tokens_total{{pool="{pool}",kind="estimated"}} 50"# + ), + format!(r#"mesh_route_cache_estimate_tokens_total{{pool="{pool}",kind="actual"}} 40"#), + ] { + assert!(rendered.contains(&line), "missing {line} in\n{rendered}"); + } + } + + #[tokio::test] + async fn grpc_cached_tokens_are_reconciled_against_the_estimate() { + assert_reconciled(&rendered(false).await, "regular"); + } + + #[tokio::test] + async fn grpc_pd_cached_tokens_are_reconciled_against_the_prefill_estimate() { + let rendered = rendered(true).await; + assert_reconciled(&rendered, "prefill"); + assert!(!rendered.contains(r#"pool="decode",kind="#), "{rendered}"); + } } diff --git a/atom/mesh/src/routers/ingress.rs b/atom/mesh/src/routers/ingress.rs index 3e44ef80f90..bc795281364 100644 --- a/atom/mesh/src/routers/ingress.rs +++ b/atom/mesh/src/routers/ingress.rs @@ -964,9 +964,15 @@ impl IngressRouting { ) -> Result { let Some(controls) = self.chat_controls.read().get(&entry.id).copied() else { let messages = routed.map_or(&chat.messages, |routed| &routed.messages); - return render_chat_messages(chat, messages, &*entry.tokenizer, &template_kwargs(chat)) - .map(|rendered| rendered.text) - .map_err(IngressError::invalid); + return render_chat_messages( + chat, + messages, + &*entry.tokenizer, + &template_kwargs(chat), + None, + ) + .map(|rendered| rendered.text) + .map_err(IngressError::invalid); }; let mut sent: serde_json::Map = serde_json::from_slice(body).map_err(|e| IngressError::invalid(e.to_string()))?; diff --git a/atom/mesh/src/routers/prepare/chat_render.rs b/atom/mesh/src/routers/prepare/chat_render.rs index faab8d7bba0..3d9ad816168 100644 --- a/atom/mesh/src/routers/prepare/chat_render.rs +++ b/atom/mesh/src/routers/prepare/chat_render.rs @@ -322,7 +322,7 @@ pub(crate) fn render_chat( ) -> Result<(String, Option), String> { let Some(controls) = controls else { let text = process_chat_messages(chat, tokenizer)?.text; - let opener = prompt_opener(&text); + let opener = prompt_opener(&text, &[THINK_OPEN.to_string()]); return Ok((text, opener)); }; let typed; diff --git a/atom/mesh/src/routers/prepare/chat_template.rs b/atom/mesh/src/routers/prepare/chat_template.rs index 5e0306452cb..bae978f0696 100644 --- a/atom/mesh/src/routers/prepare/chat_template.rs +++ b/atom/mesh/src/routers/prepare/chat_template.rs @@ -1,11 +1,17 @@ //! Chat-template rendering helpers: turn `ChatMessage` lists into the JSON //! shape that HuggingFace chat templates consume. -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; use serde_json::{json, Value}; -use super::fast_tokenizer::FastTokenizer; +use super::{ + fast_tokenizer::FastTokenizer, + message_tools::{qualified_name, MessageTools}, +}; use crate::{ core::{worker::RuntimeType, Worker}, protocols::{ @@ -86,50 +92,18 @@ pub fn process_chat_messages( &request.messages, tokenizer, &template_kwargs(request), + None, ) } -/// The label with an ATOM worker's reasoning toggle, `[name, off value, on value]`: -/// GetModelInfo's `reasoning_toggle_json`. -const REASONING_TOGGLE_LABEL: &str = "reasoning_toggle_json"; - -/// What an ATOM model's chat renders its reasoning controls with: its toggle, if any. -pub(crate) struct AtomChat { - pub toggle: Option<(String, Value, Value)>, -} - -impl AtomChat { - /// The model's, from the first of its `workers` with the toggle label. - pub(crate) fn of(workers: &[Arc]) -> Result { - let toggle = workers - .iter() - .find_map(|worker| worker.metadata().labels.get(REASONING_TOGGLE_LABEL)) - .map(|json| { - serde_json::from_str(json) - .map_err(|e| format!("Invalid {REASONING_TOGGLE_LABEL} label {json}: {e}")) - }) - .transpose()?; - Ok(Self { toggle }) - } -} - -/// The efforts ATOM's chat templates read (`VALID_TEMPLATE_EFFORTS` in -/// atom/entrypoints/openai/reasoning.py); ATOM's HTTP chat drops any other. -const ATOM_TEMPLATE_EFFORTS: [&str; 3] = ["low", "high", "max"]; - -/// As `process_chat_messages`, with the request's template kwargs over `default_kwargs`; -/// for an ATOM model (`atom`), its reasoning effort then over both as ATOM's HTTP chat -/// applies it (`apply_reasoning_controls`): "none" switches the toggle off, an effort -/// its templates read becomes `thinking_effort`. -pub fn process_chat_messages_with_defaults( +/// The kwargs a chat renders with: `default_kwargs`, then its reasoning effort and its own. +pub(crate) fn merged_template_kwargs( request: &ChatCompletionRequest, - tokenizer: &dyn Tokenizer, default_kwargs: Option<&HashMap>, - atom: Option<&AtomChat>, -) -> Result { +) -> HashMap { let mut combined_template_kwargs = default_kwargs.cloned().unwrap_or_default(); - if let (None, Some(reasoning_effort)) = (atom, &request.reasoning_effort) { + if let Some(reasoning_effort) = &request.reasoning_effort { combined_template_kwargs.insert( "reasoning_effort".to_string(), Value::String(reasoning_effort.clone()), @@ -141,53 +115,45 @@ pub fn process_chat_messages_with_defaults( combined_template_kwargs.insert(key.clone(), value.clone()); } } - let effort = request.reasoning_effort.as_deref(); - if let (Some(atom), Some(effort)) = (atom, effort) { - if let (Some((name, off, _)), "none") = (&atom.toggle, effort) { - combined_template_kwargs.insert(name.clone(), off.clone()); - } - if ATOM_TEMPLATE_EFFORTS.contains(&effort) { - let effort = Value::String(effort.to_string()); - combined_template_kwargs.insert("thinking_effort".to_string(), effort); - } - } + combined_template_kwargs +} +/// The function name a tool declares as sent. +fn sent_name(tool: &Value) -> Option<&str> { + tool.get("function")?.get("name")?.as_str() +} + +/// As `process_chat_messages`, rendered with `template_kwargs`, the merged kwargs, and +/// each message given its own `message_tools`, as ATOM's HTTP chat renders them. +pub fn process_chat_messages_with_kwargs( + request: &ChatCompletionRequest, + tokenizer: &dyn Tokenizer, + template_kwargs: &HashMap, + message_tools: Option<&MessageTools>, +) -> Result { render_chat_messages( request, &request.messages, tokenizer, - &combined_template_kwargs, + template_kwargs, + message_tools, ) } /// The template kwargs `process_chat_messages` renders `request` with. pub(crate) fn template_kwargs(request: &ChatCompletionRequest) -> HashMap { - let kwargs_capacity = 1 + request.chat_template_kwargs.as_ref().map_or(0, |k| k.len()); - let mut combined_template_kwargs = HashMap::with_capacity(kwargs_capacity); - - if let Some(reasoning_effort) = &request.reasoning_effort { - combined_template_kwargs.insert( - "reasoning_effort".to_string(), - Value::String(reasoning_effort.clone()), - ); - } - - if let Some(template_kwargs) = &request.chat_template_kwargs { - for (key, value) in template_kwargs { - combined_template_kwargs.insert(key.clone(), value.clone()); - } - } - - combined_template_kwargs + merged_template_kwargs(request, None) } -/// `process_chat_messages` with `messages` in place of the request's own and -/// `template_kwargs` as the template kwargs. +/// `process_chat_messages` with `messages` in place of the request's own, +/// `template_kwargs` as the template kwargs, and each message given its own +/// `message_tools`. pub(crate) fn render_chat_messages( request: &ChatCompletionRequest, messages: &[ChatMessage], tokenizer: &dyn Tokenizer, template_kwargs: &HashMap, + message_tools: Option<&MessageTools>, ) -> Result { let any = tokenizer.as_any(); let hf_tokenizer = any.downcast_ref::().or_else(|| { @@ -208,6 +174,14 @@ pub(crate) fn render_chat_messages( let mut transformed_messages = process_content_format(messages, content_format)?; process_tool_call_arguments(&mut transformed_messages)?; + if let Some(declared) = message_tools { + for (message, tools) in transformed_messages.iter_mut().zip(declared.0.iter()) { + if let (Some(message), Some(tools)) = (message.as_object_mut(), tools) { + let tools = serde_json::to_value(tools).map_err(|e| e.to_string())?; + message.insert("tools".to_string(), tools); + } + } + } let tools_json: Option> = request .tools @@ -220,6 +194,28 @@ pub(crate) fn render_chat_messages( }) .transpose() .map_err(|e| format!("Failed to serialize tools: {}", e))?; + // Namespaced top-level tools render as sent, those `request` keeps by name, or the + // one a namespaced named choice qualifies. + let sent = message_tools.and_then(|declared| declared.1.as_deref()); + let choice = message_tools + .and_then(MessageTools::qualified_choice) + .and_then(Result::ok); + let tools_json = match (tools_json, sent) { + (Some(_), Some(sent)) => { + let kept: HashSet<&str> = request + .tools + .iter() + .flatten() + .map(|tool| tool.function.name.as_str()) + .collect(); + let kept = sent.iter().filter(|tool| match &choice { + Some(choice) => qualified_name(tool).as_ref() == Some(choice), + None => sent_name(tool).is_some_and(|n| kept.contains(n)), + }); + Some(kept.cloned().collect()) + } + (typed, _) => typed, + }; let params = ChatTemplateParams { add_generation_prompt: true, diff --git a/atom/mesh/src/routers/prepare/generation_payload.rs b/atom/mesh/src/routers/prepare/generation_payload.rs index fe442a8632e..74278c96d20 100644 --- a/atom/mesh/src/routers/prepare/generation_payload.rs +++ b/atom/mesh/src/routers/prepare/generation_payload.rs @@ -21,6 +21,8 @@ pub struct GenerationPayload { /// REST surface; chat path leaves at `false` to match the upstream chat /// builder which does not touch this field). pub log_metrics: bool, + /// ATOM only: a chat's input to ATOM's structured-output derivation. + pub structured_output: Option, /// ATOM only: the request's DP session and its parent, from its headers. pub dp_session_id: Option, pub dp_parent_session_id: Option, @@ -28,6 +30,20 @@ pub struct GenerationPayload { pub chat_template: Option, } +/// What ATOM's HTTP chat route derives a chat's structured output from: the +/// request's fields as JSON, and how atomesh rendered its prompt. +pub struct StructuredOutput { + pub tools_json: Option, + pub tool_choice_json: Option, + pub response_format_json: Option, + /// One item per message, its own tools or null; None when no message has any. + pub message_tools_json: Option, + /// The merged template kwargs the prompt was rendered with, a JSON object. + pub chat_template_kwargs_json: String, + /// The prompt ends, trailing whitespace aside, in a marker the worker lists. + pub prompt_opens_reasoning: bool, +} + pub struct SamplingParams { pub temperature: f32, pub top_p: f32, diff --git a/atom/mesh/src/routers/prepare/inference.rs b/atom/mesh/src/routers/prepare/inference.rs index 9f1492451da..bafeb864eb5 100644 --- a/atom/mesh/src/routers/prepare/inference.rs +++ b/atom/mesh/src/routers/prepare/inference.rs @@ -538,6 +538,33 @@ impl ParsedInference { (metadata, Some(routed)) } + /// Whether a chat has a content part other than text. + pub(crate) fn chat_carries_media(chat: &ChatCompletionRequest) -> bool { + chat.messages.iter().any(|message| { + let content = match message { + ChatMessage::System { content, .. } + | ChatMessage::User { content, .. } + | ChatMessage::Tool { content, .. } + | ChatMessage::Developer { content, .. } => Some(content), + ChatMessage::Assistant { content, .. } => content.as_ref(), + ChatMessage::Function { .. } => None, + }; + let media = |part: &ContentPart| !matches!(part, ContentPart::Text { .. }); + matches!(content, Some(MessageContent::Parts(parts)) if parts.iter().any(media)) + }) + } + + /// Whether a `/generate` request has image, video, audio or embedding input. + pub(crate) fn generate_carries_media(generate: &GenerateRequest) -> bool { + let media = [ + &generate.image_data, + &generate.video_data, + &generate.audio_data, + &generate.input_embeds, + ]; + media.iter().any(|data| data.is_some()) + } + pub fn chat(&self) -> Option<&ChatCompletionRequest> { if let Self::Chat(chat) = self { Some(chat) diff --git a/atom/mesh/src/routers/prepare/message_tools.rs b/atom/mesh/src/routers/prepare/message_tools.rs new file mode 100644 index 00000000000..ea67a774973 --- /dev/null +++ b/atom/mesh/src/routers/prepare/message_tools.rs @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +// Copyright (c) 2026 ATOM Project Contributors +//! The tools a chat's messages declare themselves (Kimi-K3's dynamic tools), which ATOM's +//! HTTP chat accepts on any role while the typed request keeps them on a developer message only. + +use std::{collections::HashSet, sync::Arc}; + +use serde::Deserialize; +use serde_json::{Map, Value}; + +use crate::protocols::{ + chat::{ChatCompletionRequest, ChatMessage}, + common::Tool, +}; + +/// Each message's own tools as sent, in message order; `None` where a message declares none. +/// Beside them, the top-level tools as sent when one carries a namespace, and a named +/// `tool_choice` as sent when it carries one, which the typed request drops. +#[derive(Debug, Clone, Default)] +pub struct MessageTools( + pub Arc>>>, + pub Option>>, + pub Option>, +); + +impl MessageTools { + /// The tools each message of a chat's body as `sent` declares, on whatever role. + pub fn read(sent: &Map) -> Result { + let tools = |value: Option<&Value>| match value { + Some(value) => Option::>::deserialize(value) + .map_err(|e| format!("Invalid message tools: {e}")), + None => Ok(None), + }; + let Some(Value::Array(messages)) = sent.get("messages") else { + return Err("Invalid message tools: messages is not an array".to_string()); + }; + let namespaced = |tools: &Vec| tools.iter().any(|t| namespace(t).is_some()); + let top_level = tools(sent.get("tools"))?.filter(namespaced).map(Arc::new); + let choice = (sent.get("tool_choice")) + .filter(|c| c.is_object() && namespace(c).is_some()) + .cloned(); + let declared = Self( + Arc::new( + messages + .iter() + .map(|m| tools(m.get("tools"))) + .collect::>()?, + ), + top_level, + choice.map(Arc::new), + ); + for tool in declared.0.iter().flatten().flatten() { + qualified(tool).map_err(|e| format!("Invalid message tools: {e}"))?; + } + for tool in declared.1.iter().flat_map(|tools| tools.iter()) { + qualified(tool).map_err(|e| format!("Invalid tools: {e}"))?; + } + declared + .qualified_choice() + .transpose() + .map_err(|e| format!("Invalid tool_choice: {e}"))?; + Ok(declared) + } + + /// The named `tool_choice`'s `namespace::name`, when it carries a namespace. + pub fn qualified_choice(&self) -> Option> { + let choice = self.2.as_deref()?; + let name = choice.get("function")?.get("name")?.as_str()?; + Some(qualify(name, choice)) + } + + /// The tools the typed `req` keeps: a developer message's. + pub fn of(req: &ChatCompletionRequest) -> Self { + let tools = req.messages.iter().map(|message| match message { + ChatMessage::Developer { tools, .. } => tools.as_ref().map(|tools| { + let tools = tools.iter().map(serde_json::to_value); + tools.collect::>().unwrap_or_default() + }), + _ => None, + }); + Self(Arc::new(tools.collect()), None, None) + } + + pub fn is_empty(&self) -> bool { + self.0.iter().all(Option::is_none) + } + + /// The top-level tools, then every message's, as the reply's tool calls are read + /// against: one per name, its last declaration, as ATOM's HTTP chat reads them. + /// A namespaced tool is named `namespace::name`. + pub fn with_top_level(&self, top_level: Option<&Vec>) -> Vec { + let declared = self + .0 + .iter() + .flatten() + .flatten() + .filter_map(|t| qualified(t).ok()); + let top_level: Vec = match &self.1 { + Some(sent) => sent.iter().filter_map(|t| qualified(t).ok()).collect(), + None => top_level.into_iter().flatten().cloned().collect(), + }; + let all: Vec = top_level.into_iter().chain(declared).collect(); + let mut named = HashSet::new(); + let mut last: Vec = (all.into_iter().rev()) + .filter(|tool| named.insert(tool.function.name.clone())) + .collect(); + last.reverse(); + last + } +} + +/// `tool` named as ATOM's `qualified_tool_name` names it: `namespace::name` when it +/// has a namespace, beside or inside `function`, as a string or `{"name": ...}`. +fn qualified(tool: &Value) -> Result { + let mut parsed: Tool = serde_json::from_value(tool.clone()).map_err(|e| e.to_string())?; + parsed.function.name = qualify(&parsed.function.name, tool)?; + Ok(parsed) +} + +/// A tool as sent, named as `qualified` names it; none if it cannot be. +pub(crate) fn qualified_name(tool: &Value) -> Option { + let name = tool.get("function")?.get("name")?.as_str()?; + qualify(name, tool).ok() +} + +/// `name` qualified by the namespace `carrier` (a tool or a named choice) has. +fn qualify(name: &str, carrier: &Value) -> Result { + let namespace = match namespace(carrier) { + None => return Ok(name.to_string()), + Some(Value::Object(namespace)) => namespace.get("name"), + Some(namespace) => Some(namespace), + }; + let namespace = match namespace.and_then(Value::as_str) { + Some(namespace) if identifier(namespace) => namespace, + _ => return Err("tool namespace must be a nonempty identifier without '::'".into()), + }; + match name.split_once("::") { + Some((prefix, _)) if prefix != namespace => Err("conflicting tool namespaces".into()), + Some(_) => Ok(name.to_string()), + None => Ok(format!("{namespace}::{name}")), + } +} + +/// `tool`'s namespace as sent, beside or inside `function`; none when null or absent. +fn namespace(tool: &Value) -> Option<&Value> { + let beside = tool.get("namespace").filter(|n| !n.is_null()); + beside + .or_else(|| tool.get("function")?.get("namespace")) + .filter(|n| !n.is_null()) +} + +/// A word character, then word characters, dots or dashes. +fn identifier(name: &str) -> bool { + let word = |c: char| c.is_alphanumeric() || c == '_'; + name.starts_with(word) && name.chars().all(|c| word(c) || c == '.' || c == '-') +} diff --git a/atom/mesh/src/routers/prepare/mod.rs b/atom/mesh/src/routers/prepare/mod.rs index c3c6a4bc9c5..145e3b0357e 100644 --- a/atom/mesh/src/routers/prepare/mod.rs +++ b/atom/mesh/src/routers/prepare/mod.rs @@ -1,9 +1,11 @@ //! Transport-neutral request preparation: HTTP request → (GenerationPayload, ResponseContext). -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc, time::Instant}; use axum::response::Response; use http::HeaderMap; +use serde::Serialize; +use serde_json::Value; use tracing::error; use uuid::Uuid; @@ -13,6 +15,7 @@ use crate::{ placement::{types::RenderedTemplate, PlacementError}, steps::tokenizer_registration::loaded_template, worker::RuntimeType, + Worker, }, protocols::{ chat::ChatCompletionRequest, @@ -30,6 +33,7 @@ pub(crate) mod chat_render; pub(crate) mod chat_template; pub(crate) mod fast_tokenizer; pub mod generation_payload; +pub mod message_tools; pub(crate) mod parser_factory_lookup; pub mod response_context; pub(crate) mod stop_decoder_builder; @@ -40,14 +44,32 @@ pub(crate) mod tool_constraints; mod tests; use chat_template::{ - atom_chat_render_gap, default_template_kwargs, process_chat_messages_with_defaults, AtomChat, - ProcessedMessages, + atom_chat_render_gap, default_template_kwargs, merged_template_kwargs, + process_chat_messages_with_kwargs, ProcessedMessages, }; -use generation_payload::{GenerationPayload, LogprobConfig, SamplingParams, StopConfig}; +use generation_payload::{ + GenerationPayload, LogprobConfig, SamplingParams, StopConfig, StructuredOutput, +}; +use message_tools::MessageTools; use response_context::{ProtocolRequest, ResponseContext}; use stop_decoder_builder::create_stop_decoder; use tool_constraints::{filter_chat_request_by_tool_choice, generate_tool_constraints}; +/// The label with the markers an ATOM worker lists: GetModelInfo's `reasoning_open_markers`. +const REASONING_OPEN_MARKERS_LABEL: &str = "reasoning_open_markers"; +/// GetModelInfo's `implicit_reasoning_opener` and `reasoning_toggle_json`, as labels. +const IMPLICIT_REASONING_OPENER_LABEL: &str = "implicit_reasoning_opener"; +const REASONING_TOGGLE_LABEL: &str = "reasoning_toggle_json"; + +/// `work`, its duration recorded under `stage` as the HTTP ingress records its own stages. +fn staged(stage: &'static str, work: impl FnOnce() -> T) -> T { + let started = Instant::now(); + let done = work(); + metrics::histogram!("mesh_prepare_stage_seconds", "stage" => stage) + .record(started.elapsed().as_secs_f64()); + done +} + pub fn lookup_tokenizer( model_id: &str, registry: &TokenizerRegistry, @@ -81,17 +103,22 @@ pub fn prepare_chat( prepare_chat_with(req, headers, model_id, components, None, false) } -/// A chat's body as the client `sent` it (JSON bytes), for -/// `prepare_chat_with`, where `model` renders with an encoder of its own -/// (`chat_render`): the typed request drops or rewrites fields that encoder -/// reads (`thinking`, a system message's `tools`, `tool_choice`). A chat -/// whose model renders with a template is not parsed again. +/// A chat's body as the client `sent` it (JSON bytes), for `prepare_chat_with`, +/// where `model` renders with an encoder of its own (`chat_render`) or has an ATOM +/// worker, which reads the tools any message declares and `thinking` +/// (`MessageTools`, `read_thinking`): the typed request drops or rewrites the +/// fields these read (`thinking`, a system message's `tools`, `tool_choice`). Any +/// other chat is not parsed again. pub fn sent_chat_body( sent: &[u8], model: Option<&str>, components: &AppContext, -) -> Result>>, Response> { - if model.and_then(|m| components.chat_controls_of(m)).is_none() { +) -> Result>>, Response> { + let kept = model.is_some_and(|model| { + components.chat_controls_of(model).is_some() + || has_atom_worker(&components.worker_registry.get_by_model(model)) + }); + if !kept { return Ok(None); } serde_json::from_slice(sent) @@ -99,16 +126,24 @@ pub fn sent_chat_body( .map_err(|e| error::bad_request("invalid_request", e.to_string())) } -/// `prepare_chat`, rendering the prompt (`chat_render::render_chat`) with the -/// chat's body as `sent` where the caller has it, and, with -/// `reads_prompt_opener`, naming the opener the prompt ends on +/// Whether one of a model's `workers` is an ATOM worker. +fn has_atom_worker(workers: &[Arc]) -> bool { + workers + .iter() + .any(|worker| worker.metadata().runtime_type == RuntimeType::Atom) +} + +/// `prepare_chat`, rendering the prompt with the chat's body as `sent` where the +/// caller has it: an encoder reads it (`chat_render::render_chat`), and for a model +/// with an ATOM worker, so do the tools its messages declare and its `thinking`. +/// With `reads_prompt_opener`, names the opener the prompt ends on /// (`ResponseContext::prompt_opener`). pub fn prepare_chat_with( req: Arc, headers: Option, model_id: Option, components: &AppContext, - sent: Option<&serde_json::Map>, + sent: Option<&serde_json::Map>, reads_prompt_opener: bool, ) -> Result<(GenerationPayload, ResponseContext), Response> { let model_id_str = model_id.as_deref().ok_or_else(|| { @@ -143,36 +178,53 @@ pub fn prepare_chat_with( .map_err(|e| error::internal_error("invalid_default_template_kwargs", e))?; let body_ref = filter_chat_request_by_tool_choice(&req); - let atom = workers - .iter() - .any(|worker| worker.metadata().runtime_type == RuntimeType::Atom) - .then(|| AtomChat::of(&workers)) - .transpose() - .map_err(|e| error::internal_error("invalid_reasoning_toggle", e))?; + let atom = has_atom_worker(&workers); + // Only ATOM reads the tools a message declares, and `thinking`: from the chat as + // sent where the caller has it. + let message_tools = match (atom, sent) { + (false, _) => None, + (true, Some(sent)) => Some( + MessageTools::read(sent).map_err(|e| error::bad_request("invalid_message_tools", e))?, + ), + (true, None) => Some(MessageTools::of(&req)), + } + .filter(|declared| !declared.is_empty() || declared.1.is_some() || declared.2.is_some()); + let thinking = sent.filter(|_| atom).and_then(read_thinking); - let (text, prompt_opener) = match controls { - Some(_) => chat_render::render_chat(&body_ref, sent, &*tokenizer, controls), - None => process_chat_messages_with_defaults( + let template_kwargs = if atom { + let toggle = reasoning_toggle(&workers) + .map_err(|e| error::internal_error("invalid_reasoning_toggle", e))?; + atom_template_kwargs( &body_ref, - &*tokenizer, + thinking.as_ref(), default_kwargs.as_ref(), - atom.as_ref(), + toggle, ) - .map(|processed| { - let opener = response_context::prompt_opener(&processed.text); - (processed.text, opener) - }), + .map_err(|e| error::bad_request("invalid_reasoning_effort", e))? + } else { + merged_template_kwargs(&body_ref, default_kwargs.as_ref()) + }; + let (text, rendered_opener) = match controls { + Some(_) => chat_render::render_chat(&body_ref, sent, &*tokenizer, controls) + .map(|(text, opener)| (text, Some(opener))), + None => staged("template", || { + process_chat_messages_with_kwargs( + &body_ref, + &*tokenizer, + &template_kwargs, + message_tools.as_ref(), + ) + }) + .map(|processed| (processed.text, None)), } .map_err(|e| error::bad_request("process_messages_failed", e))?; let processed = ProcessedMessages { text, stop_sequences: body_ref.stop.clone(), }; - let encoding = tokenizer - .encode(&processed.text, false) + let encoding = staged("encode", || tokenizer.encode(&processed.text, false)) .map_err(|e| error::internal_error("tokenization_failed", format!("{}", e)))?; let token_ids = encoding.token_ids().to_vec(); - let prompt_opener = prompt_opener.filter(|_| reads_prompt_opener); let tool_constraints = if let Some(tools) = body_ref.tools.as_ref() { generate_tool_constraints(tools, &req.tool_choice, &req.model) @@ -181,6 +233,35 @@ pub fn prepare_chat_with( None }; + let prompt_opener = match rendered_opener { + // A prompt its encoder rendered names its own opener. + Some(opener) if atom || reads_prompt_opener => opener, + Some(_) => None, + None if atom => { + let markers = reasoning_open_markers(&workers) + .map_err(|e| error::internal_error("invalid_structured_output", e))?; + response_context::prompt_opener(&processed.text, &markers) + } + None if reads_prompt_opener => { + let think = [response_context::THINK_OPEN.to_string()]; + response_context::prompt_opener(&processed.text, &think) + } + None => None, + }; + let structured_output = atom + .then(|| { + let opens = prompt_opener.is_some(); + structured_output(&req, message_tools.as_ref(), &template_kwargs, opens) + }) + .transpose() + .map_err(|e| error::internal_error("invalid_structured_output", e))?; + // Else the opener the model's reply starts after unprompted, unless switched off. + let prompt_opener = match prompt_opener { + None if atom => implicit_reasoning_opener(&workers, &template_kwargs) + .map_err(|e| error::internal_error("invalid_reasoning_toggle", e))?, + opener => opener, + }; + let stop_decoder = create_stop_decoder( &tokenizer, req.stop.as_ref(), @@ -197,6 +278,7 @@ pub fn prepare_chat_with( &processed.text, token_ids, tool_constraints, + structured_output, ); (payload.dp_session_id, payload.dp_parent_session_id) = dp_session_ids(headers.as_ref()); if controls.is_none() { @@ -216,8 +298,17 @@ pub fn prepare_chat_with( .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); + // The reply's tool calls are read against every tool the chat declares; none + // declared, ATOM's HTTP chat parses none. + let rendered_for = match &message_tools { + Some(declared) => Arc::new(ChatCompletionRequest { + tools: Some(declared.with_top_level(req.tools.as_ref())).filter(|t| !t.is_empty()), + ..(*req).clone() + }), + None => Arc::clone(&req), + }; let ctx = ResponseContext { - original: ProtocolRequest::Chat(Arc::clone(&req)), + original: ProtocolRequest::Chat(rendered_for), model_id, headers, original_text: Some(processed.text.clone()), @@ -231,6 +322,8 @@ pub fn prepare_chat_with( configured_tool_parser: components.configured_tool_parser.clone(), configured_reasoning_parser: components.configured_reasoning_parser.clone(), prompt_opener, + reads_as_atom: false, + usage_on_finish: false, }; Ok((payload, ctx)) @@ -287,6 +380,8 @@ pub fn prepare_generate( configured_tool_parser: components.configured_tool_parser.clone(), configured_reasoning_parser: components.configured_reasoning_parser.clone(), prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, }; Ok((payload, ctx)) @@ -319,6 +414,7 @@ pub(crate) fn build_chat_payload( text: &str, token_ids: Vec, tool_constraints: Option<(String, String)>, + structured_output: Option, ) -> GenerationPayload { use crate::protocols::common::{ToolChoice, ToolChoiceValue}; @@ -368,12 +464,171 @@ pub(crate) fn build_chat_payload( stream: req.stream, return_hidden_states: req.return_hidden_states, log_metrics: false, + structured_output, dp_session_id: None, dp_parent_session_id: None, chat_template: None, } } +/// The markers an ATOM worker of the model lists as opening reasoning; none if none does. +fn reasoning_open_markers(workers: &[Arc]) -> Result, String> { + Ok(workers + .iter() + .find_map(|worker| worker.metadata().labels.get(REASONING_OPEN_MARKERS_LABEL)) + .map(|json| { + serde_json::from_str(json) + .map_err(|e| format!("Invalid {REASONING_OPEN_MARKERS_LABEL} label {json}: {e}")) + }) + .transpose()? + .unwrap_or_default()) +} + +/// The efforts ATOM's chat templates read (`VALID_TEMPLATE_EFFORTS` in +/// atom/entrypoints/openai/reasoning.py); ATOM's HTTP chat drops any other. +const ATOM_TEMPLATE_EFFORTS: [&str; 3] = ["low", "high", "max"]; + +/// An ATOM worker's reasoning toggle, `[name, off value, on value]`, from GetModelInfo. +fn reasoning_toggle(workers: &[Arc]) -> Result, String> { + let labels = workers.iter().map(|w| &w.metadata().labels); + labels + .filter_map(|labels| labels.get(REASONING_TOGGLE_LABEL)) + .next() + .map(|json| { + serde_json::from_str(json) + .map_err(|e| format!("Invalid {REASONING_TOGGLE_LABEL} label {json}: {e}")) + }) + .transpose() +} + +/// The kwargs ATOM's HTTP chat renders `request` with: the defaults, the request's own, +/// then its `thinking` and `reasoning_effort` resolved (`resolve_reasoning_controls`) +/// and applied (`apply_reasoning_controls`): a stated toggle sets `toggle`, an effort +/// becomes `thinking_effort`. +fn atom_template_kwargs( + request: &ChatCompletionRequest, + thinking: Option<&Value>, + default_kwargs: Option<&HashMap>, + toggle: Option<(String, Value, Value)>, +) -> Result, String> { + let mut kwargs = default_kwargs.cloned().unwrap_or_default(); + if let Some(own) = &request.chat_template_kwargs { + kwargs.extend(own.iter().map(|(key, value)| (key.clone(), value.clone()))); + } + let (enabled, effort) = reasoning_controls(thinking, request.reasoning_effort.as_deref())?; + if let (Some((name, off, on)), Some(enabled)) = (toggle, enabled) { + kwargs.insert(name, if enabled { on } else { off }); + } + if let Some(effort) = effort { + kwargs.insert("thinking_effort".into(), effort); + } + Ok(kwargs) +} + +/// Whether thinking is on, if stated, and the effort, as ATOM's HTTP chat resolves its +/// `thinking` and `reasoning_effort` (`resolve_reasoning_controls`, chat rules). +fn reasoning_controls( + thinking: Option<&Value>, + effort: Option<&str>, +) -> Result<(Option, Option), String> { + let field = |name: &str| { + let value = thinking.and_then(Value::as_object)?.get(name); + value.filter(|value| !value.is_null()) + }; + let mut enabled = field("type").map(|kind| kind.as_str() != Some("disabled")); + if effort == Some("none") { + enabled = Some(false); + } + let effort = field("effort") + .cloned() + .or_else(|| effort.map(|e| Value::String(e.into()))); + let effort = match effort { + Some(Value::Bool(_)) => { + return Err("reasoning effort must be an integer in [1, 100]".into()) + } + Some(Value::Number(n)) if n.is_f64() => { + return Err("reasoning effort must be an integer in [1, 100]".into()) + } + Some(Value::Number(n)) => match n.as_i64() { + Some(1..=100) => Some(Value::Number(n)), + _ => return Err("reasoning effort must be an integer in [1, 100]".into()), + }, + Some(Value::String(e)) if ATOM_TEMPLATE_EFFORTS.contains(&e.as_str()) => { + Some(Value::String(e)) + } + _ => None, + }; + Ok((enabled, effort)) +} + +/// A chat's `thinking` control as `sent`, which the typed request has no field for. +pub fn read_thinking(sent: &serde_json::Map) -> Option { + sent.get("thinking") + .filter(|value| !value.is_null()) + .cloned() +} + +/// The opener an ATOM worker of the model reports its replies start after with no +/// prompt opener (GetModelInfo's `implicit_reasoning_opener`), unless `kwargs` hold the +/// off value of its reasoning toggle: `reasoning_channel` in ATOM's HTTP server. +fn implicit_reasoning_opener( + workers: &[Arc], + kwargs: &HashMap, +) -> Result, String> { + let Some(labels) = workers + .iter() + .map(|w| &w.metadata().labels) + .find(|labels| labels.contains_key(IMPLICIT_REASONING_OPENER_LABEL)) + else { + return Ok(None); + }; + let toggle: Option<(String, Value, Value)> = labels + .get(REASONING_TOGGLE_LABEL) + .map(|json| { + serde_json::from_str(json) + .map_err(|e| format!("Invalid {REASONING_TOGGLE_LABEL} label {json}: {e}")) + }) + .transpose()?; + let switched_off = toggle.is_some_and(|(name, off, _)| kwargs.get(&name) == Some(&off)); + Ok((!switched_off).then(|| labels[IMPLICIT_REASONING_OPENER_LABEL].clone())) +} + +/// What an ATOM worker's chat route derives `req`'s structured output from: its fields +/// as sent, the `kwargs` its prompt rendered with, and whether that prompt opens reasoning. +fn structured_output( + req: &ChatCompletionRequest, + message_tools: Option<&MessageTools>, + kwargs: &HashMap, + prompt_opens_reasoning: bool, +) -> Result { + // Namespaced top-level tools go as sent: the typed ones lost their namespace. + let top_level = message_tools.and_then(|declared| declared.1.as_deref()); + let tools_json = match top_level { + Some(sent) => Some(to_json(sent)?), + None => req.tools.as_ref().map(to_json).transpose()?, + }; + // A namespaced named choice goes as sent too, so ATOM names it as it names the tool. + let tool_choice_json = match message_tools.and_then(|declared| declared.2.as_deref()) { + Some(sent) => Some(to_json(sent)?), + None => req.tool_choice.as_ref().map(to_json).transpose()?, + }; + Ok(StructuredOutput { + tools_json, + tool_choice_json, + response_format_json: req.response_format.as_ref().map(to_json).transpose()?, + message_tools_json: message_tools + .filter(|declared| !declared.is_empty()) + .map(|declared| to_json(declared.0.as_ref())) + .transpose()?, + chat_template_kwargs_json: to_json(kwargs)?, + prompt_opens_reasoning, + }) +} + +fn to_json(value: &T) -> Result { + serde_json::to_string(value).map_err(|e| e.to_string()) +} + pub(crate) fn build_generate_payload( request_id: String, req: &GenerateRequest, @@ -422,6 +677,7 @@ pub(crate) fn build_generate_payload( stream: req.stream, return_hidden_states: req.return_hidden_states, log_metrics: req.log_metrics, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, @@ -433,8 +689,7 @@ fn resolve_generate_input( tokenizer: &Arc, ) -> Result<(Option, Vec), String> { if let Some(text) = &req.text { - let encoding = tokenizer - .encode(text, false) + let encoding = staged("encode", || tokenizer.encode(text, false)) .map_err(|e| format!("Tokenization failed: {}", e))?; return Ok((Some(text.clone()), encoding.token_ids().to_vec())); } diff --git a/atom/mesh/src/routers/prepare/response_context.rs b/atom/mesh/src/routers/prepare/response_context.rs index 4580db2adee..27957966aef 100644 --- a/atom/mesh/src/routers/prepare/response_context.rs +++ b/atom/mesh/src/routers/prepare/response_context.rs @@ -42,23 +42,28 @@ pub struct ResponseContext { pub reasoning_parser_factory: Option, pub configured_tool_parser: Option, pub configured_reasoning_parser: Option, - /// The channel opener the rendered prompt ends on (see - /// [`prompt_opener`]): the reply starts inside that block, with no opener - /// of its own, so the reasoning parser reads this one before the reply. - /// ``, or a model's own when its prompt is rendered outside the - /// router (Kimi-K3's `<|open|>think<|sep|>` / `<|open|>response<|sep|>`). + /// The channel opener the rendered prompt ends on (see [`prompt_opener`]), or the one + /// the model's replies start after unprompted (DeepSeek-R1's): the reply starts inside + /// that block, with no opener of its own, so the reasoning parser reads this one before + /// the reply. Kept only for a reply read as ATOM's. pub prompt_opener: Option, + /// The reply is ATOM's (`AtomOutput`), and takes the shape ATOM's HTTP chat gives + /// it: content "" when empty, and a stream opened by an empty assistant delta. + pub reads_as_atom: bool, + /// ATOM puts this model's streamed usage on the finish chunk, not a usage-only chunk + /// after it (GetModelInfo's `usage_on_finish`). + pub usage_on_finish: bool, } /// The opener a `` template's generation prompt can end on. pub const THINK_OPEN: &str = ""; -/// The Python server's `prompt_starts_in_reasoning` for the `` -/// dialect: the opener, when the prompt (trailing whitespace aside) ends -/// with it. -pub fn prompt_opener(prompt: &str) -> Option { - prompt - .trim_end() - .ends_with(THINK_OPEN) - .then(|| THINK_OPEN.to_string()) +/// ATOM's `prompt_starts_in_reasoning`: the marker among `markers` (GetModelInfo's +/// `reasoning_open_markers`) that the prompt, trailing whitespace aside, ends with. +pub fn prompt_opener(prompt: &str, markers: &[String]) -> Option { + let prompt = prompt.trim_end(); + markers + .iter() + .find(|marker| !marker.is_empty() && prompt.ends_with(marker.as_str())) + .cloned() } diff --git a/atom/mesh/src/routers/prepare/tests.rs b/atom/mesh/src/routers/prepare/tests.rs index 5bec0a7f193..4f631e6d486 100644 --- a/atom/mesh/src/routers/prepare/tests.rs +++ b/atom/mesh/src/routers/prepare/tests.rs @@ -989,6 +989,7 @@ mod e_generation_payload { stream: false, return_hidden_states: false, log_metrics: false, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, @@ -1139,6 +1140,8 @@ mod f_response_context { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -1187,6 +1190,8 @@ mod f_response_context { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, }; assert_eq!(ctx.headers.as_ref().unwrap().get("x-trace").unwrap(), "abc"); } @@ -1210,6 +1215,8 @@ mod f_response_context { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, }; assert!(ctx.processed_messages.is_none()); } @@ -1326,6 +1333,26 @@ mod h_prepare_chat_generate { assert_eq!(payload.text, pm.text); } + #[test] + fn test_prepare_chat_records_its_template_and_encode_stages() { + let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder(); + let metrics = recorder.handle(); + let _recorder = metrics::set_default_local_recorder(&recorder); + let components = test_mocks::app_context_with_hf_tokenizer("m"); + prepare_chat( + chat_req(false), + None, + Some("m".to_string()), + components.as_ref(), + ) + .expect("HF tokenizer must succeed"); + let rendered = metrics.render(); + for stage in ["template", "encode"] { + let count = format!("mesh_prepare_stage_seconds_count{{stage=\"{stage}\"}} 1"); + assert!(rendered.lines().any(|line| line == count), "{rendered}"); + } + } + #[test] fn test_only_a_router_that_asks_reads_the_prompts_opener() { // The test template renders `user: `, so this prompt ends @@ -1651,3 +1678,476 @@ mod h_prepare_chat_generate { assert!(!std::any::type_name::().contains("mesh_grpc")); } } + +mod i_atom_structured_output { + use std::sync::Arc; + + use serde_json::{json, Value}; + + use crate::core::{worker::RuntimeType, BasicWorkerBuilder}; + use crate::protocols::chat::ChatCompletionRequest; + use crate::routers::prepare::{ + generation_payload::GenerationPayload, + message_tools::MessageTools, + prepare_chat, prepare_chat_with, + response_context::{ProtocolRequest, ResponseContext}, + }; + use crate::routers::test_mocks; + + /// `body` prepared for model "m", whose one worker runs `runtime` with `labels`. + fn prepare(body: Value, runtime: RuntimeType, labels: &[(&str, &str)]) -> GenerationPayload { + prepared(body, runtime, labels).0 + } + + /// As `prepare`, with its response context. + fn prepared( + body: Value, + runtime: RuntimeType, + labels: &[(&str, &str)], + ) -> (GenerationPayload, ResponseContext) { + let ctx = test_mocks::app_context_with_hf_tokenizer("m"); + let mut worker = BasicWorkerBuilder::new("grpc://worker:1") + .runtime_type(runtime) + .model_id("m") + // An ATOM worker reporting none has its chats refused. + .label("chat_template", "{{ messages }}"); + test_mocks::app_context::loaded_with_worker_template(&ctx, "m", "{{ messages }}"); + for (key, value) in labels { + worker = worker.label(*key, *value); + } + ctx.worker_registry.register(Arc::new(worker.build())); + let request: ChatCompletionRequest = serde_json::from_value(body).unwrap(); + prepare_chat(Arc::new(request), None, Some("m".into()), &ctx).unwrap() + } + + fn parsed(json: Option) -> Option { + json.map(|json| serde_json::from_str(&json).unwrap()) + } + + #[test] + fn an_atom_chats_reasoning_effort_reaches_its_kwargs_as_atoms_http_chat_applies_it() { + let toggle = ( + "reasoning_toggle_json", + r#"["enable_thinking", false, true]"#, + ); + let defaults = ( + "default_chat_template_kwargs_json", + r#"{"enable_thinking": true}"#, + ); + let kwargs = |effort: &str, labels: &[(&str, &str)]| { + let body = json!({ + "model": "m", "messages": [{"role": "user", "content": "hi"}], + "reasoning_effort": effort, + }); + let (payload, _) = prepared(body, RuntimeType::Atom, labels); + parsed(Some( + payload.structured_output.unwrap().chat_template_kwargs_json, + )) + }; + // "none" switches reasoning off over a default that has it on, and sets no effort. + let off = Some(json!({"enable_thinking": false})); + assert_eq!(kwargs("none", &[toggle, defaults]), off); + assert_eq!(kwargs("none", &[toggle]), off); + // A template effort is `thinking_effort`; another one is dropped. + let high = Some(json!({"enable_thinking": true, "thinking_effort": "high"})); + assert_eq!(kwargs("high", &[toggle, defaults]), high); + assert_eq!(kwargs("medium", &[toggle]), Some(json!({}))); + } + + #[test] + fn an_atom_chats_thinking_reaches_its_kwargs_as_atoms_http_chat_resolves_it() { + let kwargs = |controls: Value, default_on: bool| { + let ctx = test_mocks::app_context_with_hf_tokenizer("m"); + let defaults = json!({"enable_thinking": default_on}).to_string(); + let worker = BasicWorkerBuilder::new("grpc://worker:1") + .runtime_type(RuntimeType::Atom) + .model_id("m") + .label("chat_template", "{{ messages }}") + .label( + "reasoning_toggle_json", + r#"["enable_thinking", false, true]"#, + ) + .label("default_chat_template_kwargs_json", defaults); + ctx.worker_registry.register(Arc::new(worker.build())); + test_mocks::app_context::loaded_with_worker_template(&ctx, "m", "{{ messages }}"); + let mut body = json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]}); + body.as_object_mut() + .unwrap() + .extend(controls.as_object().unwrap().clone()); + let sent = body.as_object().unwrap().clone(); + let request: ChatCompletionRequest = serde_json::from_value(body).unwrap(); + let model = Some("m".to_string()); + let prepared = + prepare_chat_with(Arc::new(request), None, model, &ctx, Some(&sent), false); + let carried = prepared.unwrap().0.structured_output.unwrap(); + parsed(Some(carried.chat_template_kwargs_json)).unwrap() + }; + let disabled = json!({"thinking": {"type": "disabled"}}); + assert_eq!(kwargs(disabled, true), json!({"enable_thinking": false})); + let enabled = json!({"thinking": {"type": "enabled"}}); + assert_eq!(kwargs(enabled, false), json!({"enable_thinking": true})); + // thinking.effort sets the effort; a top-level "none" still switches it off. + let effort = json!({"thinking": {"effort": "high"}}); + let expected = json!({"enable_thinking": true, "thinking_effort": "high"}); + assert_eq!(kwargs(effort, true), expected); + let none = json!({"thinking": {"type": "enabled"}, "reasoning_effort": "none"}); + assert_eq!(kwargs(none, true), json!({"enable_thinking": false})); + } + + #[test] + fn an_atom_chat_carries_its_fields_as_sent_its_kwargs_and_its_reasoning_opening() { + let tool = + |name: &str| json!({"type": "function", "function": {"name": name, "parameters": {}}}); + let format = json!({"type": "json_schema", "json_schema": {"name": "a", "schema": {}}}); + // The named choice narrows the tools atomesh renders, not those it carries. + let body = json!({ + "model": "m", + "messages": [ + {"role": "developer", "content": "d", "tools": [tool("lookup")]}, + {"role": "user", "content": "hi \n"}, + ], + "tools": [tool("ping"), tool("pong")], + "tool_choice": {"type": "function", "function": {"name": "pong"}}, + "response_format": format, + "reasoning_effort": "high", + "chat_template_kwargs": {"flag": "request"}, + }); + let labels = [ + ( + "default_chat_template_kwargs_json", + r#"{"flag": "default", "kept": 1}"#, + ), + ("reasoning_open_markers", r#"["", ""]"#), + ]; + let (payload, ctx) = prepared(body.clone(), RuntimeType::Atom, &labels); + + assert!(payload.text.ends_with("hi \n"), "{}", payload.text); + // The marker it ends on is read before the reply. + assert_eq!(ctx.prompt_opener.as_deref(), Some("")); + let carried = payload.structured_output.expect("an ATOM chat carries one"); + assert_eq!(parsed(carried.tools_json), Some(body["tools"].clone())); + assert_eq!( + parsed(carried.tool_choice_json), + Some(body["tool_choice"].clone()) + ); + assert_eq!(parsed(carried.response_format_json), Some(format)); + let message_tools = json!([[tool("lookup")], null]); + assert_eq!(parsed(carried.message_tools_json), Some(message_tools)); + let kwargs = json!({"flag": "request", "kept": 1, "thinking_effort": "high"}); + assert_eq!( + parsed(Some(carried.chat_template_kwargs_json)), + Some(kwargs) + ); + assert!(carried.prompt_opens_reasoning); + } + + #[test] + fn a_plain_atom_chat_carries_no_fields_and_its_prompt_opens_no_reasoning() { + let body = json!({"model": "m", "messages": [{"role": "user", "content": " hi"}]}); + let labels = [("reasoning_open_markers", r#"[""]"#)]; + let (payload, ctx) = prepared(body, RuntimeType::Atom, &labels); + assert_eq!(ctx.prompt_opener, None); + let carried = payload.structured_output.expect("an ATOM chat carries one"); + + let fields = [ + carried.tools_json, + carried.tool_choice_json, + carried.response_format_json, + carried.message_tools_json, + ]; + assert_eq!(fields, [None, None, None, None]); + assert_eq!(carried.chat_template_kwargs_json, "{}"); + assert!(!carried.prompt_opens_reasoning); + } + + /// DeepSeek-R1's template closes a it never opens: its reply starts in + /// reasoning, unless the render switched reasoning off. + #[test] + fn an_atom_chat_reads_an_implicit_opener_unless_reasoning_is_switched_off() { + let labels = [ + ("reasoning_open_markers", r#"[""]"#), + ("implicit_reasoning_opener", ""), + ("reasoning_toggle_json", r#"["thinking", false, true]"#), + ]; + let chat = |kwargs: Value| { + json!({"model": "m", "messages": [{"role": "user", "content": "hi"}], + "chat_template_kwargs": kwargs}) + }; + for (kwargs, opener) in [ + (json!({}), Some("")), + (json!({"thinking": true}), Some("")), + (json!({"thinking": false}), None), + ] { + let (payload, ctx) = prepared(chat(kwargs.clone()), RuntimeType::Atom, &labels); + assert_eq!(ctx.prompt_opener.as_deref(), opener, "{kwargs}"); + // The prompt itself opens none; ATOM adds the implicit start itself. + assert!(!payload.structured_output.unwrap().prompt_opens_reasoning); + } + } + + /// A chat for a model with an ATOM worker keeps its body as sent, where ATOM reads the + /// tools any message declares and `thinking`; one for another backend, without encoder + /// controls, does not. + #[test] + fn a_chat_body_is_kept_as_sent_for_a_model_with_an_atom_worker() { + use crate::routers::prepare::sent_chat_body; + + let body = json!({"model": "m", "messages": [], "thinking": {"type": "enabled"}}); + let sent = serde_json::to_vec(&body).unwrap(); + for (runtime, kept) in [(RuntimeType::Atom, true), (RuntimeType::Sglang, false)] { + let ctx = test_mocks::app_context_with_hf_tokenizer("m"); + let worker = BasicWorkerBuilder::new("grpc://worker:1") + .runtime_type(runtime) + .model_id("m") + .build(); + ctx.worker_registry.register(Arc::new(worker)); + let found = sent_chat_body(&sent, Some("m"), &ctx).unwrap(); + assert_eq!(found.is_some(), kept, "ATOM worker: {kept}"); + } + } + + #[test] + fn a_chat_to_an_sglang_or_vllm_worker_carries_none() { + let body = json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]}); + for runtime in [RuntimeType::Sglang, RuntimeType::Vllm] { + let payload = prepare(body.clone(), runtime, &[]); + assert!(payload.structured_output.is_none()); + } + } + + /// `body` prepared for model "m" with its body as sent, as the gRPC routers prepare + /// it; its one worker runs `runtime`. + fn prepared_as_sent(body: Value, runtime: RuntimeType) -> (GenerationPayload, ResponseContext) { + let ctx = test_mocks::app_context_with_hf_tokenizer("m"); + let worker = BasicWorkerBuilder::new("grpc://worker:1") + .runtime_type(runtime) + .model_id("m") + .label("chat_template", "{{ messages }}"); + ctx.worker_registry.register(Arc::new(worker.build())); + test_mocks::app_context::loaded_with_worker_template(&ctx, "m", "{{ messages }}"); + let sent = body.as_object().unwrap().clone(); + let request: ChatCompletionRequest = serde_json::from_value(body).unwrap(); + let model = Some("m".to_string()); + prepare_chat_with(Arc::new(request), None, model, &ctx, Some(&sent), false).unwrap() + } + + fn tool_names(ctx: &ResponseContext) -> Vec { + let ProtocolRequest::Chat(req) = &ctx.original else { + unreachable!() + }; + let tools = req.tools.iter().flatten(); + tools.map(|tool| tool.function.name.clone()).collect() + } + + #[test] + fn an_atom_chat_carries_the_tools_a_message_of_any_role_declares() { + let tool = + |name: &str| json!({"type": "function", "function": {"name": name, "parameters": {}}}); + let body = json!({ + "model": "m", + "messages": [ + {"role": "system", "content": "be brief", "tools": [tool("lookup")]}, + {"role": "user", "content": "hi", "tools": [tool("fetch")]}, + ], + "tools": [tool("ping")], + }); + // The typed request keeps a message's tools on a developer message only. + let typed: ChatCompletionRequest = serde_json::from_value(body.clone()).unwrap(); + assert!(serde_json::to_value(&typed.messages).unwrap()[0] + .get("tools") + .is_none()); + + let (payload, ctx) = prepared_as_sent(body, RuntimeType::Atom); + let carried = payload.structured_output.expect("an ATOM chat carries one"); + let declared = json!([[tool("lookup")], [tool("fetch")]]); + assert_eq!(parsed(carried.message_tools_json), Some(declared)); + // The reply's tool calls are read against all of them. + assert_eq!(tool_names(&ctx), ["ping", "lookup", "fetch"]); + } + + #[test] + fn a_tool_declared_again_is_read_with_its_last_declaration() { + let search = |limit: &str| { + json!({"type": "function", "function": {"name": "search", "parameters": + {"type": "object", "properties": {"limit": {"type": limit}}}}}) + }; + let fetch = json!({"type": "function", "function": {"name": "fetch", "parameters": {}}}); + let body = json!({ + "model": "m", + "messages": [ + {"role": "system", "content": "be brief", "tools": [search("string"), fetch]}, + {"role": "user", "content": "hi"}, + ], + "tools": [search("integer")], + }); + let (payload, ctx) = prepared_as_sent(body, RuntimeType::Atom); + // ATOM gets both declarations as sent; the reply is read with the last. + let carried = payload.structured_output.expect("an ATOM chat carries one"); + let declared = json!([[search("string"), fetch], null]); + assert_eq!(parsed(carried.message_tools_json), Some(declared)); + assert_eq!(tool_names(&ctx), ["search", "fetch"]); + let ProtocolRequest::Chat(req) = &ctx.original else { + unreachable!() + }; + let read = serde_json::to_value(&req.tools.as_ref().unwrap()[0]).unwrap(); + assert_eq!(read, search("string")); + } + + /// A namespaced tool reaches the template and ATOM as sent, and its calls are read + /// as `namespace::name`, as ATOM's HTTP chat reads them, so two namespaces' `search` + /// stay apart. + #[test] + fn a_namespaced_message_tool_keeps_its_namespace() { + let search = |namespace: Value| { + json!({"type": "function", "namespace": namespace, + "function": {"name": "search", "parameters": {}}}) + }; + let (files, web) = (search(json!("files")), search(json!({"name": "web"}))); + let body = json!({"model": "m", "messages": [ + {"role": "system", "content": "be brief", "tools": [files.clone(), web.clone()]}, + {"role": "user", "content": "hi"}, + ]}); + let (payload, ctx) = prepared_as_sent(body.clone(), RuntimeType::Atom); + let carried = payload.structured_output.expect("an ATOM chat carries one"); + let declared = json!([[files, web], null]); + assert_eq!(parsed(carried.message_tools_json), Some(declared)); + assert_eq!(tool_names(&ctx), ["files::search", "web::search"]); + + use crate::routers::prepare::chat_template::process_chat_messages_with_kwargs; + use crate::tokenizer::{traits::Tokenizer, HuggingFaceTokenizer}; + let mut tokenizer = + HuggingFaceTokenizer::from_file(test_mocks::tokenizer::hf_tokenizer_path()).unwrap(); + let template = "{% for m in messages %}{% for t in m.tools or [] %}\ + {{ t.namespace.name or t.namespace }}.{{ t.function.name }};{% endfor %}{% endfor %}"; + tokenizer.set_chat_template(template.to_string()).unwrap(); + let declared = MessageTools::read(body.as_object().unwrap()).unwrap(); + let request: ChatCompletionRequest = serde_json::from_value(body).unwrap(); + let kwargs = Default::default(); + let rendered = + process_chat_messages_with_kwargs(&request, &tokenizer, &kwargs, Some(&declared)); + assert_eq!(rendered.unwrap().text, "files.search;web.search;"); + } + + /// A namespaced top-level tool reaches the template and ATOM as sent, and its calls + /// are read as `namespace::name`, as ATOM's HTTP chat reads them. + #[test] + fn a_namespaced_top_level_tool_keeps_its_namespace() { + let search = |namespace: &str| { + json!({"type": "function", "namespace": namespace, + "function": {"name": "search", "parameters": {}}}) + }; + let (files, web) = (search("files"), search("web")); + let body = json!({"model": "m", "tools": [files.clone(), web.clone()], + "messages": [{"role": "user", "content": "hi"}]}); + let (payload, ctx) = prepared_as_sent(body.clone(), RuntimeType::Atom); + let carried = payload.structured_output.expect("an ATOM chat carries one"); + assert_eq!(parsed(carried.tools_json), Some(json!([files, web]))); + assert_eq!(carried.message_tools_json, None); + assert_eq!(tool_names(&ctx), ["files::search", "web::search"]); + + use crate::routers::prepare::chat_template::process_chat_messages_with_kwargs; + use crate::tokenizer::{traits::Tokenizer, HuggingFaceTokenizer}; + let mut tokenizer = + HuggingFaceTokenizer::from_file(test_mocks::tokenizer::hf_tokenizer_path()).unwrap(); + let template = "{% for t in tools %}{{ t.namespace }}.{{ t.function.name }};{% endfor %}"; + tokenizer.set_chat_template(template.to_string()).unwrap(); + let declared = MessageTools::read(body.as_object().unwrap()).unwrap(); + let request: ChatCompletionRequest = serde_json::from_value(body).unwrap(); + let kwargs = Default::default(); + let rendered = + process_chat_messages_with_kwargs(&request, &tokenizer, &kwargs, Some(&declared)); + assert_eq!(rendered.unwrap().text, "files.search;web.search;"); + } + + /// A named choice with a namespace reaches ATOM as sent, which reads it as + /// `files::search` beside the tool it names, and the prompt keeps that tool alone. + #[test] + fn a_namespaced_named_choice_keeps_its_namespace() { + let search = |namespace: &str| { + json!({"type": "function", "namespace": namespace, + "function": {"name": "search", "parameters": {}}}) + }; + let choice = json!({"type": "function", "namespace": "files", + "function": {"name": "search"}}); + let body = json!({"model": "m", "tools": [search("files"), search("web")], + "tool_choice": choice.clone(), "messages": [{"role": "user", "content": "hi"}]}); + let (payload, _) = prepared_as_sent(body.clone(), RuntimeType::Atom); + let carried = payload.structured_output.expect("an ATOM chat carries one"); + assert_eq!(parsed(carried.tool_choice_json), Some(choice)); + + use crate::routers::prepare::chat_template::process_chat_messages_with_kwargs; + use crate::routers::prepare::tool_constraints::filter_chat_request_by_tool_choice; + use crate::tokenizer::{traits::Tokenizer, HuggingFaceTokenizer}; + let mut tokenizer = + HuggingFaceTokenizer::from_file(test_mocks::tokenizer::hf_tokenizer_path()).unwrap(); + let template = "{% for t in tools %}{{ t.namespace }}.{{ t.function.name }};{% endfor %}"; + tokenizer.set_chat_template(template.to_string()).unwrap(); + let declared = MessageTools::read(body.as_object().unwrap()).unwrap(); + let request: ChatCompletionRequest = serde_json::from_value(body).unwrap(); + let kept = filter_chat_request_by_tool_choice(&request); + let kwargs = Default::default(); + let rendered = + process_chat_messages_with_kwargs(&kept, &tokenizer, &kwargs, Some(&declared)); + assert_eq!(rendered.unwrap().text, "files.search;"); + } + + #[test] + fn a_tool_with_two_namespaces_is_refused() { + let tool = json!({"type": "function", "namespace": "files", + "function": {"name": "web::search", "parameters": {}}}); + let body = json!({"messages": [{"role": "system", "tools": [tool]}]}); + let read = MessageTools::read(body.as_object().unwrap()); + assert!(read.is_err_and(|e| e.contains("conflicting tool namespaces"))); + } + + #[test] + fn a_message_declaring_an_empty_tool_list_leaves_tool_parsing_off() { + // ATOM's HTTP chat parses no tool call when the chat declares no tool. + let body = json!({"model": "m", "messages": [ + {"role": "system", "content": "be brief", "tools": []}, + {"role": "user", "content": "hi"}, + ]}); + let (payload, ctx) = prepared_as_sent(body, RuntimeType::Atom); + let carried = payload.structured_output.expect("an ATOM chat carries one"); + assert_eq!(parsed(carried.message_tools_json), Some(json!([[], null]))); + let ProtocolRequest::Chat(req) = &ctx.original else { + unreachable!() + }; + assert!(req.tools.is_none()); + } + + #[test] + fn the_template_sees_each_message_s_own_tools() { + use crate::routers::prepare::chat_template::process_chat_messages_with_kwargs; + use crate::tokenizer::{traits::Tokenizer, HuggingFaceTokenizer}; + + let mut tokenizer = + HuggingFaceTokenizer::from_file(test_mocks::tokenizer::hf_tokenizer_path()).unwrap(); + let template = "{% for m in messages %}{{ m.role }}\ + {% for t in m.tools or [] %}+{{ t.function.name }}{% endfor %};{% endfor %}"; + tokenizer.set_chat_template(template.to_string()).unwrap(); + let tool = json!({"type": "function", "function": {"name": "lookup", "parameters": {}}}); + let body = json!({"model": "m", "messages": [ + {"role": "system", "content": "be brief", "tools": [tool]}, + {"role": "user", "content": "hi"}, + ]}); + let declared = MessageTools::read(body.as_object().unwrap()).unwrap(); + let request: ChatCompletionRequest = serde_json::from_value(body).unwrap(); + let kwargs = Default::default(); + let rendered = + process_chat_messages_with_kwargs(&request, &tokenizer, &kwargs, Some(&declared)); + assert_eq!(rendered.unwrap().text, "system+lookup;user;"); + } + + #[test] + fn a_chat_to_an_sglang_worker_keeps_its_top_level_tools() { + let tool = json!({"type": "function", "function": {"name": "lookup", "parameters": {}}}); + let body = json!({ + "model": "m", + "messages": [{"role": "system", "content": "be brief", "tools": [tool]}], + }); + let (payload, ctx) = prepared_as_sent(body, RuntimeType::Sglang); + assert!(!payload.text.contains("lookup"), "{}", payload.text); + assert!(tool_names(&ctx).is_empty()); + } +} diff --git a/atom/mesh/src/routers/render/atom_usage.rs b/atom/mesh/src/routers/render/atom_usage.rs index fbd629ed3f0..9b28638ed62 100644 --- a/atom/mesh/src/routers/render/atom_usage.rs +++ b/atom/mesh/src/routers/render/atom_usage.rs @@ -1,11 +1,10 @@ -//! ATOM's additions to an OpenAI `usage`, as `serving_chat.py` and -//! `serving_completion.py` write them: the prefix-cache hit -//! (`prompt_tokens_details.cached_tokens`, the first sibling's), the slowest -//! sibling's `ttft_s` / `tpot_s` / `latency_s`, and `num_choices` past one, -//! on a chat; a completion's are not carried yet. -//! Only ATOM workers, the standalone backend and gRPC workers, set -//! `WorkerMeta.timing`; for any other the usage is left as it is. +// SPDX-License-Identifier: MIT +// Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +// Copyright (c) 2026 ATOM Project Contributors +//! ATOM's additions to an OpenAI `usage`, as `serving_chat.py` and `serving_completion.py` +//! write them; only an ATOM worker's sequences carry the timing (`WorkerMeta.timing`). +use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use crate::routers::token_handle::token_chunk::{SeqTiming, TokenChunk, WorkerMeta}; @@ -27,9 +26,33 @@ pub(crate) const CHAT_STREAM: Fields = Fields { cached_tokens: true, timing: false, }; +/// A completion, not streamed. +pub(crate) const COMPLETION: Fields = Fields { + cached_tokens: false, + timing: true, +}; + +/// A sequence's timing under the `/generate` meta_info keys it travels in to the +/// completions adapter. +#[derive(Serialize, Deserialize)] +pub(crate) struct MetaInfoTiming { + ttft_s: f64, + tpot_s: f64, + latency_s: f64, +} + +impl From for MetaInfoTiming { + fn from(timing: SeqTiming) -> Self { + Self { + ttft_s: timing.ttft, + tpot_s: timing.tpot, + latency_s: timing.latency, + } + } +} pub(crate) struct AtomUsage { - /// The prompt the siblings share, which a chat counts once. + /// The prompt the siblings share, which ATOM counts once. prompt_tokens: Option, cached_tokens: u32, timing: SeqTiming, @@ -37,8 +60,8 @@ pub(crate) struct AtomUsage { } impl AtomUsage { - /// The request's, from its siblings' metas in index order; none unless - /// the backend timed them. + /// The request's, from its siblings' metas in index order: the first one's cached + /// tokens and the slowest timing; none unless ATOM timed them. pub fn of<'a>(metas: impl IntoIterator) -> Option { let mut usage: Option = None; for meta in metas { @@ -75,10 +98,36 @@ impl AtomUsage { Some(usage) } + /// The request's, from the `/generate` meta_infos carrying `MetaInfoTiming`. + pub fn of_meta_infos(meta_infos: &[&Value]) -> Option { + let metas = meta_infos + .iter() + .map(|info| { + let timing = MetaInfoTiming::deserialize(*info).ok()?; + let cached = info.get("cached_tokens").and_then(Value::as_f64); + Some(WorkerMeta { + cached_tokens: cached.unwrap_or(0.0) as u32, + timing: Some(SeqTiming { + ttft: timing.ttft_s, + tpot: timing.tpot_s, + latency: timing.latency_s, + }), + ..Default::default() + }) + }) + .collect::>>()?; + let mut usage = Self::of(&metas)?; + usage.prompt_tokens = meta_infos + .first() + .and_then(|info| info.get("prompt_tokens")?.as_u64()) + .map(|tokens| tokens as u32); + Some(usage) + } + /// Add this endpoint's `fields` to the `usage` object. pub fn extend(&self, usage: &mut Map, fields: Fields) { if let (Some(prompt), true) = (self.prompt_tokens, self.choices > 1) { - // Summed over the siblings by the render; the server counts it once. + // Summed over the siblings by the render; ATOM counts it once. let completion = usage .get("completion_tokens") .and_then(Value::as_u64) @@ -103,7 +152,7 @@ impl AtomUsage { } /// `response` serialized, its `usage` extended with `fields`. - pub fn extend_response( + pub fn extend_response( &self, response: &T, fields: Fields, diff --git a/atom/mesh/src/routers/render/chat_aggregator.rs b/atom/mesh/src/routers/render/chat_aggregator.rs index 1cec263f3cc..89e1e3b518d 100644 --- a/atom/mesh/src/routers/render/chat_aggregator.rs +++ b/atom/mesh/src/routers/render/chat_aggregator.rs @@ -11,7 +11,7 @@ use tracing::error; use crate::{ protocols::{ chat::{ChatChoice, ChatCompletionMessage, ChatCompletionRequest, ChatCompletionResponse}, - common::{FunctionCallResponse, ToolCall, ToolChoice, ToolChoiceValue, Usage}, + common::{FunctionCallResponse, Tool, ToolCall, ToolChoice, ToolChoiceValue, Usage}, }, reasoning_parser::{ParserFactory as ReasoningParserFactory, ParserResult}, routers::{ @@ -40,7 +40,7 @@ use crate::{ traits::Tokenizer, }, tool_parser::{ - registry::{check_tool_parser_availability, get_tool_parser}, + registry::{check_tool_parser_availability, create_reply_tool_parser, get_tool_parser}, ParserFactory as ToolParserFactory, }, }; @@ -50,7 +50,7 @@ pub async fn process(stream: TokenHandle, ctx: ResponseContext) -> Response { Ok((resp, None)) => axum::Json(resp).into_response(), Ok((resp, Some(atom))) => match atom.extend_response(&resp, atom_usage::CHAT) { Ok(value) => axum::Json(value).into_response(), - Err(e) => error::internal_error("serialize_failed", e.to_string()), + Err(e) => error::internal_error("serialization_failed", e.to_string()), }, Err(resp) => resp, } @@ -60,10 +60,10 @@ pub async fn process_typed( stream: TokenHandle, ctx: ResponseContext, ) -> Result { - aggregate(stream, ctx).await.map(|(resp, _)| resp) + Ok(aggregate(stream, ctx).await?.0) } -/// The response, and ATOM's usage additions where the backend has them. +/// The response, and ATOM's usage additions where an ATOM worker answered. async fn aggregate( stream: TokenHandle, ctx: ResponseContext, @@ -136,6 +136,7 @@ async fn aggregate( ctx.configured_tool_parser.as_deref(), ctx.configured_reasoning_parser.as_deref(), ctx.prompt_opener.as_deref(), + ctx.reads_as_atom, ) .await; match res { @@ -195,6 +196,7 @@ async fn process_choice( configured_tool_parser: Option<&str>, configured_reasoning_parser: Option<&str>, prompt_opener: Option<&str>, + reads_as_atom: bool, ) -> Result { let (token_ids, finish_reason, matched_stop, logprobs) = match complete { TokenChunk::Complete { @@ -259,12 +261,14 @@ async fn process_choice( ); if tool_choice_enabled && chat_request.tools.is_some() { - let used_json_schema = match &chat_request.tool_choice { - Some(ToolChoice::Function { .. }) => true, - Some(ToolChoice::Value(ToolChoiceValue::Required)) => true, - Some(ToolChoice::AllowedTools { mode, .. }) => mode == "required", - _ => false, - }; + // ATOM derives a forced choice's format itself: the model's own tool syntax. + let used_json_schema = !reads_as_atom + && match &chat_request.tool_choice { + Some(ToolChoice::Function { .. }) => true, + Some(ToolChoice::Value(ToolChoiceValue::Required)) => true, + Some(ToolChoice::AllowedTools { mode, .. }) => mode == "required", + _ => false, + }; if used_json_schema { (tool_calls, processed_text) = parse_json_schema_response( @@ -275,14 +279,41 @@ async fn process_choice( ); } else if tool_available { if let Some(factory) = tool_parser_factory { - (tool_calls, processed_text) = parse_tool_calls( - factory, - configured_tool_parser, - &processed_text, - &chat_request.model, - history_tool_calls_count, - ) - .await; + let tools = chat_request.tools.as_deref().unwrap_or_default(); + // An ATOM reply cut off inside a native call is read with the call closed. + let closers = match reads_as_atom { + true => { + let model = &chat_request.model; + let (text, configured) = (&processed_text, configured_tool_parser); + cut_off_call_closers(factory, configured, model, text, tools).await + } + false => None, + }; + let closed = closers.map(|closers| format!("{processed_text}{closers}")); + let parse = |text: String| { + let model = &chat_request.model; + async move { + let parsed = parse_tool_calls( + factory, + configured_tool_parser, + &text, + tools, + model, + history_tool_calls_count, + reads_as_atom, + ) + .await; + parsed + } + }; + let mut parsed = None; + if let Some(closed) = closed { + parsed = Some(parse(closed).await).filter(|(calls, _)| calls.is_some()); + } + (tool_calls, processed_text) = match parsed { + Some(parsed) => parsed, + None => parse(std::mem::take(&mut processed_text)).await, + }; } } } @@ -307,11 +338,8 @@ async fn process_choice( index, message: ChatCompletionMessage { role: "assistant".to_string(), - content: if processed_text.is_empty() { - None - } else { - Some(processed_text) - }, + // ATOM's HTTP chat answers "" when empty; None leaves the key out. + content: (reads_as_atom || !processed_text.is_empty()).then_some(processed_text), tool_calls, reasoning_content: reasoning_text, }, @@ -326,13 +354,11 @@ async fn process_choice( /// refuses a longer text outright. const ONE_SHOT_MAX_BYTES: usize = 65536; -/// A whole reply (`text`, decoded as `pieces`) split into content and -/// reasoning; `opener`, the prompt's own, is read before it. -/// -/// A reply the one-shot parse would refuse goes through a fresh parser's -/// streaming path a piece at a time, as a streamed reply does, so its buffer -/// holds only what one piece leaves pending; the result is trimmed as the -/// one-shot parse trims it. +/// Fed last to the piece-by-piece parse: no reasoning delimiter starts with it. +pub(super) const RELEASE: &str = "\0"; + +/// A whole reply (`text`, decoded as `pieces`) split into content and reasoning, the +/// prompt's `opener` read first; one over the one-shot limit is parsed piece by piece. async fn split_reasoning( factory: &ReasoningParserFactory, configured: Option<&str>, @@ -355,7 +381,9 @@ async fn split_reasoning( let Some(mut parser) = create_reasoning_parser(factory, configured, model) else { return Ok(ParserResult::normal(text.to_string())); }; - let (mut normal, mut reasoning, mut entered) = (String::new(), String::new(), false); + // A parser that starts inside reasoning (deepseek_r1) has entered it before any piece. + let entered = parser.is_in_reasoning(); + let (mut normal, mut reasoning, mut entered) = (String::new(), String::new(), entered); for piece in opener.into_iter().chain(pieces.iter().map(String::as_str)) { let result = parser .parse_reasoning_streaming_incremental(piece) @@ -364,33 +392,55 @@ async fn split_reasoning( normal.push_str(&result.normal_text); reasoning.push_str(&result.reasoning_text); } + // A last piece that could start a delimiter ("<", ", + model: &str, + text: &str, + tools: &[Tool], +) -> Option { + let mut parser = create_reply_tool_parser(factory, configured, model, true)?; + parser.parse_incremental(text, tools).await.ok()?; + parser.end_of_input_closers(tools) } async fn parse_tool_calls( factory: &ToolParserFactory, configured: Option<&str>, text: &str, + tools: &[Tool], model: &str, history_tool_calls_count: usize, + reads_as_atom: bool, ) -> (Option>, String) { - let pooled = get_tool_parser(factory, configured, model); + // An ATOM worker's reply is read by a parser of its own, set to read it as ATOM's. + let own = reads_as_atom.then(|| create_reply_tool_parser(factory, configured, model, true)); + let pooled = match own.flatten() { + Some(parser) => Arc::new(tokio::sync::Mutex::new(parser)), + None => get_tool_parser(factory, configured, model), + }; let result = { let parser = pooled.lock().await; - parser.parse_complete(text).await + // The declared schemas type each argument, as the streamed reply's parser has them. + parser.parse_complete_with_tools(text, tools).await }; match result { Ok((normal_text, parsed)) => { @@ -503,13 +553,28 @@ mod split_reasoning_tests { } async fn split(parts: &[&str], opener: Option<&str>) -> ParserResult { + split_by("qwen3", parts, opener).await + } + + async fn split_by(parser: &str, parts: &[&str], opener: Option<&str>) -> ParserResult { let factory = ReasoningParserFactory::new(); let text = parts.concat(); - split_reasoning(&factory, Some("qwen3"), "m", &pieces(parts), &text, opener) + split_reasoning(&factory, Some(parser), "m", &pieces(parts), &text, opener) .await .unwrap() } + #[tokio::test] + async fn a_long_reply_closing_an_empty_implicit_reasoning_block_drops_the_marker() { + // deepseek_r1 starts inside reasoning: its first piece closes an empty block. + for len in [100, ONE_SHOT_MAX_BYTES + 1000] { + let answer = "a".repeat(len); + let result = split_by("deepseek_r1", &["", &answer], None).await; + assert!(result.reasoning_text.is_empty(), "len {len}"); + assert_eq!(result.normal_text, answer, "len {len}"); + } + } + #[tokio::test] async fn a_reply_over_the_one_shot_limit_splits_as_a_short_one_does() { for len in [100, ONE_SHOT_MAX_BYTES + 1000] { @@ -532,4 +597,26 @@ mod split_reasoning_tests { let result = split(&["plain", "", "Done."], None).await; assert!(result.reasoning_text.is_empty()); } + + #[tokio::test] + async fn a_long_reply_keeps_its_answer_s_whitespace() { + let thought = "z".repeat(ONE_SHOT_MAX_BYTES + 1000); + let result = split(&["", &thought, "", " print(1)\n"], None).await; + assert_eq!(result.reasoning_text, thought); + assert_eq!(result.normal_text, " print(1)\n"); + } + + #[tokio::test] + async fn a_reply_ending_in_a_delimiter_s_first_characters_keeps_them() { + for len in [100, ONE_SHOT_MAX_BYTES + 1000] { + let thought = "z".repeat(len); + // Generation ended inside reasoning, then after it, on a lone "<" or "", &thought, "<"], None).await; + assert_eq!(result.reasoning_text, format!("{thought}<"), "len {len}"); + assert!(result.normal_text.is_empty(), "len {len}"); + let result = split(&["", &thought, "", "3 ", " true, - Some(ToolChoice::Value(ToolChoiceValue::Required)) => true, - Some(ToolChoice::AllowedTools { mode, .. }) => mode == "required", - _ => false, - }; - let is_specific_function = matches!(tool_choice, Some(ToolChoice::Function { .. })); + // ATOM derives a forced choice's format itself: the model's own tool syntax. + let used_json_schema = !ctx.reads_as_atom + && match tool_choice { + Some(ToolChoice::Function { .. }) => true, + Some(ToolChoice::Value(ToolChoiceValue::Required)) => true, + Some(ToolChoice::AllowedTools { mode, .. }) => mode == "required", + _ => false, + }; + let is_specific_function = + used_json_schema && matches!(tool_choice, Some(ToolChoice::Function { .. })); let tool_parser_available = tools.is_some() && ctx @@ -141,8 +147,14 @@ async fn run_chat_stream( let mut matched_stop_value: Option = None; let mut prompt_tokens: u32 = 0; let mut completion_tokens: u32 = 0; - let mut atom_extras: Option = None; + let mut atom_usage: Option = None; let mut has_tool_call = false; + let include_usage = stream_options + .as_ref() + .is_some_and(|opts| opts.include_usage.unwrap_or(false)); + // As ATOM's HTTP chat_finish_frames: on the finish chunk, or a usage-only chunk after it. + let usage_on_finish = ctx.usage_on_finish; + let null_usage = usage_on_finish && include_usage; let mut stop_decoder = ctx.stop_decoder; @@ -150,8 +162,43 @@ async fn run_chat_stream( let mut tool_parser: Option>>> = None; let mut sse_buffer = Vec::with_capacity(512); - while let Some(item) = stream.next().await { - let chunk = item.map_err(engine_error_to_string)?; + let mut consumed = 0; + let mut held: Option = None; + loop { + let chunk = match held.take() { + Some(chunk) => chunk, + None => match stream.next().await { + Some(item) => item.map_err(engine_error_to_string)?, + None => break, + }, + }; + // A Complete's ids past the partials' are streamed first, as one more partial. + // In pieces, so no delta outgrows the reasoning and tool parsers' buffers. + let chunk = match unstreamed(&chunk, consumed, SUFFIX_PIECE) { + Some(rest) => { + let logprobs = unstreamed_logprobs(&chunk, consumed, rest.len()); + held = Some(chunk); + TokenChunk::Partial { + token_ids: rest, + logprobs, + } + } + None => chunk, + }; + if let TokenChunk::Partial { token_ids, .. } = &chunk { + consumed += token_ids.len(); + } + if is_first && ctx.reads_as_atom { + // On the engine's first message, text or not, as ATOM's HTTP chat opens its stream. + let first_chunk = ChatCompletionStreamResponse::builder(request_id, model) + .created(created) + .add_choice_content(INDEX, "assistant", "") + .maybe_system_fingerprint(system_fingerprint.clone()) + .build(); + format_sse_chunk_into(&mut sse_buffer, &first_chunk, null_usage); + send_bytes(tx, &sse_buffer, "first chunk")?; + is_first = false; + } match chunk { TokenChunk::Partial { token_ids, @@ -162,7 +209,8 @@ async fn run_chat_stream( } completion_tokens += token_ids.len() as u32; - let (chunk_text, _stopped) = process_chunk_tokens(&mut stop_decoder, &token_ids); + let (pieces, _stopped) = process_chunk_pieces(&mut stop_decoder, &token_ids); + let chunk_text = pieces.concat(); if chunk_text.is_empty() { continue; } @@ -173,7 +221,7 @@ async fn run_chat_stream( .add_choice_role(INDEX, "assistant") .maybe_system_fingerprint(system_fingerprint.clone()) .build(); - format_sse_chunk_into(&mut sse_buffer, &first_chunk); + format_sse_chunk_into(&mut sse_buffer, &first_chunk, null_usage); send_bytes(tx, &sse_buffer, "first chunk")?; is_first = false; } @@ -182,7 +230,7 @@ async fn run_chat_stream( let in_reasoning = if reasoning_parser_available { let (normal_text, reasoning_chunk, in_reasoning) = process_reasoning_stream( - &delta, + &pieces, &mut reasoning_parser, ctx.reasoning_parser_factory.as_ref(), ctx.configured_reasoning_parser.as_deref(), @@ -194,7 +242,7 @@ async fn run_chat_stream( ) .await; if let Some(c) = reasoning_chunk { - format_sse_chunk_into(&mut sse_buffer, &c); + format_sse_chunk_into(&mut sse_buffer, &c, null_usage); send_bytes(tx, &sse_buffer, "reasoning chunk")?; } delta = normal_text; @@ -235,12 +283,13 @@ async fn run_chat_stream( system_fingerprint.as_deref(), history_tool_calls_count, used_json_schema, + ctx.reads_as_atom, ) .await }; for c in tool_chunks { - format_sse_chunk_into(&mut sse_buffer, &c); + format_sse_chunk_into(&mut sse_buffer, &c, null_usage); send_bytes(tx, &sse_buffer, "tool call chunk")?; } continue; @@ -255,7 +304,7 @@ async fn run_chat_stream( .add_choice_content_with_logprobs(INDEX, "assistant", delta, chat_logprobs) .maybe_system_fingerprint(system_fingerprint.clone()) .build(); - format_sse_chunk_into(&mut sse_buffer, &content_chunk); + format_sse_chunk_into(&mut sse_buffer, &content_chunk, null_usage); send_bytes(tx, &sse_buffer, "content chunk")?; } } @@ -266,21 +315,84 @@ async fn run_chat_stream( meta, .. } => { - if let SequenceDecoderOutput::Text(text) = stop_decoder.flush() { - if !text.is_empty() { - let chunk = ChatCompletionStreamResponse::builder(request_id, model) - .created(created) - .add_choice_content(INDEX, "assistant", text) - .maybe_system_fingerprint(system_fingerprint.clone()) - .build(); - format_sse_chunk_into(&mut sse_buffer, &chunk); - send_bytes(tx, &sse_buffer, "flushed content")?; + let mut text = match stop_decoder.flush() { + SequenceDecoderOutput::Text(text) => text, + _ => String::new(), + }; + // The reasoning parser holds a last "<" or " Value::String(s), @@ -293,6 +405,47 @@ async fn run_chat_stream( } } + // An ATOM reply cut off inside a native call has the call closed, as its parser + // reads one at end of input. + if let (Some(parser), Some(tools), true) = (&tool_parser, tools.as_ref(), ctx.reads_as_atom) { + let closers = parser.lock().await.end_of_input_closers(tools); + if let Some(closers) = closers { + let chunks = process_tool_calls_stream( + &closers, + &mut tool_parser, + &mut has_tool_call, + tools, + ctx.tool_parser_factory.as_ref(), + ctx.configured_tool_parser.as_deref(), + request_id, + model, + created, + system_fingerprint.as_deref(), + history_tool_calls_count, + used_json_schema, + ctx.reads_as_atom, + ) + .await; + for c in chunks { + format_sse_chunk_into(&mut sse_buffer, &c, null_usage); + send_bytes(tx, &sse_buffer, "cut-off tool call")?; + } + } + // What it held as the start of a call that never came is text. + let held = match &tool_parser { + Some(parser) => parser.lock().await.end_of_input_text(), + None => String::new(), + }; + if !held.is_empty() { + let chunk = ChatCompletionStreamResponse::builder(request_id, model) + .created(created) + .add_choice_content(INDEX, "assistant", held) + .maybe_system_fingerprint(system_fingerprint.clone()) + .build(); + format_sse_chunk_into(&mut sse_buffer, &chunk, null_usage); + send_bytes(tx, &sse_buffer, "held text")?; + } + } if let Some(parser) = &tool_parser { let guard = parser.lock().await; if let Some(unstreamed) = guard.get_unstreamed_tool_args() { @@ -315,14 +468,25 @@ async fn run_chat_stream( .add_choice_tool_call_delta(INDEX, delta) .maybe_system_fingerprint(system_fingerprint.clone()) .build(); - let s = serde_json::to_string(&chunk) - .map_err(|e| format!("Failed to serialize tool chunk: {}", e))?; - tx.send(Ok(Bytes::from(format!("data: {}\n\n", s)))) - .map_err(|_| "send unstreamed".to_string())?; + format_sse_chunk_into(&mut sse_buffer, &chunk, null_usage); + send_bytes(tx, &sse_buffer, "unstreamed tool args")?; } } } + let usage = Usage { + prompt_tokens, + completion_tokens, + total_tokens: prompt_tokens + completion_tokens, + completion_tokens_details: None, + }; + // The chunk that carries the usage, with ATOM's fields (the cached tokens) for ATOM's. + let with_usage = |chunk: &ChatCompletionStreamResponse| match &atom_usage { + None => serde_json::to_string(chunk), + Some(atom) => atom + .extend_response(chunk, atom_usage::CHAT_STREAM) + .map(|v| v.to_string()), + }; if let Some(fr) = finish_reason_str { let final_fr = if has_tool_call && fr == "stop" { "tool_calls".to_string() @@ -333,35 +497,26 @@ async fn run_chat_stream( .created(created) .add_choice_finish_reason(INDEX, final_fr, matched_stop_value) .maybe_system_fingerprint(system_fingerprint.clone()) + .maybe_usage(usage_on_finish.then(|| usage.clone())) .build(); - let s = serde_json::to_string(&chunk) - .map_err(|e| format!("Failed to serialize finish chunk: {}", e))?; + let s = + with_usage(&chunk).map_err(|e| format!("Failed to serialize finish chunk: {}", e))?; tx.send(Ok(Bytes::from(format!("data: {}\n\n", s)))) .map_err(|_| "send finish".to_string())?; } - if let Some(opts) = stream_options { - if opts.include_usage.unwrap_or(false) { - let usage_chunk = ChatCompletionStreamResponse::builder(request_id, model) - .created(created) - .usage(Usage { - prompt_tokens, - completion_tokens, - total_tokens: prompt_tokens + completion_tokens, - completion_tokens_details: None, - }) - .maybe_system_fingerprint(system_fingerprint.clone()) - .build(); - let s = match &atom_extras { - None => serde_json::to_string(&usage_chunk), - Some(atom) => atom - .extend_response(&usage_chunk, atom_usage::CHAT_STREAM) - .map(|v| v.to_string()), - } + // ATOM's HTTP chat ends every stream with its usage chunk unless the finish chunk + // carries it (`chat_finish_frames`); SGLang's and vLLM's only under include_usage. + if !usage_on_finish && (include_usage || atom_usage.is_some()) { + let usage_chunk = ChatCompletionStreamResponse::builder(request_id, model) + .created(created) + .usage(usage) + .maybe_system_fingerprint(system_fingerprint.clone()) + .build(); + let s = with_usage(&usage_chunk) .map_err(|e| format!("Failed to serialize usage chunk: {}", e))?; - tx.send(Ok(Bytes::from(format!("data: {}\n\n", s)))) - .map_err(|_| "send usage".to_string())?; - } + tx.send(Ok(Bytes::from(format!("data: {}\n\n", s)))) + .map_err(|_| "send usage".to_string())?; } stream.mark_completed(); @@ -380,11 +535,70 @@ async fn run_chat_stream( Ok(()) } +/// The most ids of a Complete's unstreamed suffix sent as one delta. +const SUFFIX_PIECE: usize = 256; + +/// The first `limit` ids of a Complete past the `consumed` its partials streamed: +/// SGLang's and vLLM's carry every output id, ATOM's streamed one none. +pub(super) fn unstreamed(chunk: &TokenChunk, consumed: usize, limit: usize) -> Option> { + match chunk { + TokenChunk::Complete { token_ids, .. } => token_ids + .get(consumed..) + .filter(|rest| !rest.is_empty()) + .map(|rest| rest[..rest.len().min(limit)].to_vec()), + TokenChunk::Partial { .. } => None, + } +} + +/// The logprobs of those ids, where the Complete's cover every id it carries. +pub(super) fn unstreamed_logprobs( + chunk: &TokenChunk, + consumed: usize, + limit: usize, +) -> Option { + match chunk { + TokenChunk::Complete { + token_ids, + logprobs: Some(logprobs), + .. + } if logprobs.items.len() == token_ids.len() => Some(TokenLogprobs { + items: logprobs + .items + .get(consumed..)? + .iter() + .take(limit) + .cloned() + .collect(), + }), + _ => None, + } +} + pub(super) fn process_chunk_tokens( stop_decoder: &mut StopSequenceDecoder, token_ids: &[u32], ) -> (String, bool) { - let mut chunk_text = String::new(); + let mut text = String::new(); + let stopped = decode_chunk(stop_decoder, token_ids, |piece| text.push_str(&piece)); + (text, stopped) +} + +/// `process_chunk_tokens`, the text in the pieces the decoder wrote it in. +fn process_chunk_pieces( + stop_decoder: &mut StopSequenceDecoder, + token_ids: &[u32], +) -> (Vec, bool) { + let mut pieces = Vec::new(); + let stopped = decode_chunk(stop_decoder, token_ids, |piece| pieces.push(piece)); + (pieces, stopped) +} + +/// Decodes `token_ids`, handing each piece of text to `write`; whether a stop was hit. +fn decode_chunk( + stop_decoder: &mut StopSequenceDecoder, + token_ids: &[u32], + mut write: impl FnMut(String), +) -> bool { for &token_id in token_ids { match stop_decoder.process_token(token_id).unwrap_or_else(|e| { debug!( @@ -393,21 +607,21 @@ pub(super) fn process_chunk_tokens( ); SequenceDecoderOutput::Held }) { - SequenceDecoderOutput::Text(t) => chunk_text.push_str(&t), + SequenceDecoderOutput::Text(t) => write(t), SequenceDecoderOutput::StoppedWithText(t) => { - chunk_text.push_str(&t); - return (chunk_text, true); + write(t); + return true; } - SequenceDecoderOutput::Stopped => return (chunk_text, true), + SequenceDecoderOutput::Stopped => return true, SequenceDecoderOutput::Held => {} } } - (chunk_text, false) + false } #[allow(clippy::too_many_arguments)] async fn process_reasoning_stream( - delta: &str, + pieces: &[String], reasoning_parser: &mut Option>>>, factory: Option<&ReasoningParserFactory>, configured: Option<&str>, @@ -420,7 +634,7 @@ async fn process_reasoning_stream( if reasoning_parser.is_none() { let factory = match factory { Some(f) => f, - None => return (delta.to_string(), None, false), + None => return (pieces.concat(), None, false), }; match create_reasoning_parser(factory, configured, model) { Some(mut p) => { @@ -431,17 +645,26 @@ async fn process_reasoning_stream( } *reasoning_parser = Some(Arc::new(tokio::sync::Mutex::new(p))); } - None => return (delta.to_string(), None, false), + None => return (pieces.concat(), None, false), } } let parser_arc = match reasoning_parser { Some(p) => p.clone(), - None => return (delta.to_string(), None, false), + None => return (pieces.concat(), None, false), }; let (parse_result, in_reasoning) = { let mut parser = parser_arc.lock().await; - let result = parser.parse_reasoning_streaming_incremental(delta); + // Piece by piece, as the decoder wrote them: the parser holds a delimiter's start + // only when that is all it is given, so a piece of ids may end inside one. + let result = pieces + .iter() + .try_fold(ParserResult::default(), |mut read, piece| { + let piece = parser.parse_reasoning_streaming_incremental(piece)?; + read.normal_text.push_str(&piece.normal_text); + read.reasoning_text.push_str(&piece.reasoning_text); + Ok::<_, ParseError>(read) + }); let in_reasoning = parser.is_in_reasoning(); (result, in_reasoning) }; @@ -465,7 +688,7 @@ async fn process_reasoning_stream( } Err(e) => { warn!("Reasoning parsing error: {}", e); - (delta.to_string(), None, false) + (pieces.concat(), None, false) } } } @@ -521,6 +744,7 @@ async fn process_tool_calls_stream( system_fingerprint: Option<&str>, history_tool_calls_count: usize, use_json_parser: bool, + reads_as_atom: bool, ) -> Vec { let mut chunks = Vec::new(); if tool_parser.is_none() { @@ -533,7 +757,7 @@ async fn process_tool_calls_stream( } else { configured }; - match create_tool_parser(factory, configured, model) { + match create_reply_tool_parser(factory, configured, model, reads_as_atom) { Some(p) => *tool_parser = Some(Arc::new(tokio::sync::Mutex::new(p))), None => return chunks, } @@ -592,10 +816,23 @@ async fn process_tool_calls_stream( } #[inline] -fn format_sse_chunk_into(buffer: &mut Vec, chunk: &ChatCompletionStreamResponse) { +fn format_sse_chunk_into( + buffer: &mut Vec, + chunk: &ChatCompletionStreamResponse, + null_usage: bool, +) { buffer.clear(); buffer.extend_from_slice(b"data: "); - if let Err(e) = serde_json::to_writer(&mut *buffer, chunk) { + let written = if null_usage && chunk.usage.is_none() { + // ATOM's `usage: null` on each chunk before the one carrying the usage. + serde_json::to_value(chunk).and_then(|mut value| { + value["usage"] = Value::Null; + serde_json::to_writer(&mut *buffer, &value) + }) + } else { + serde_json::to_writer(&mut *buffer, chunk) + }; + if let Err(e) = written { error!("Failed to serialize SSE chunk: {}", e); buffer.clear(); buffer.extend_from_slice(b"data: "); diff --git a/atom/mesh/src/routers/render/generate_aggregator.rs b/atom/mesh/src/routers/render/generate_aggregator.rs index 917f1b93214..be882a57847 100644 --- a/atom/mesh/src/routers/render/generate_aggregator.rs +++ b/atom/mesh/src/routers/render/generate_aggregator.rs @@ -5,6 +5,7 @@ use std::time::Instant; use axum::response::{IntoResponse, Response}; use futures::StreamExt; +use serde::Serialize; use serde_json::Value; use crate::{ @@ -12,7 +13,10 @@ use crate::{ routers::{ comm::error, prepare::response_context::{ProtocolRequest, ResponseContext}, - render::logprob_conversion::{input_logprobs_to_generate, output_logprobs_to_generate}, + render::{ + atom_usage::MetaInfoTiming, + logprob_conversion::{input_logprobs_to_generate, output_logprobs_to_generate}, + }, token_handle::{ engine_error::EngineError, token_chunk::{FinishReason, MatchedStop, TokenChunk}, @@ -47,6 +51,7 @@ pub async fn process(stream: TokenHandle, ctx: ResponseContext) -> Response { let mut stop_decoder = ctx.stop_decoder; let mut result_array = Vec::with_capacity(completes.len()); + let mut metas = Vec::with_capacity(completes.len()); for complete in &completes { let (token_ids, finish_reason, matched_stop, usage, meta, output_lp, input_lp) = @@ -113,6 +118,7 @@ pub async fn process(stream: TokenHandle, ctx: ResponseContext) -> Response { (None, None) }; + metas.push(meta); result_array.push(GenerateResponse { text: decoded_text, output_ids: token_ids.clone(), @@ -134,7 +140,37 @@ pub async fn process(stream: TokenHandle, ctx: ResponseContext) -> Response { }); } - axum::Json(result_array).into_response() + if metas.iter().all(|meta| meta.timing.is_none()) { + return axum::Json(result_array).into_response(); + } + // An ATOM worker's: each sequence's timing, which /v1/completions reports. + let timed: Vec<_> = (result_array.iter().zip(metas)) + .map(|(response, meta)| TimedResponse { + text: &response.text, + output_ids: &response.output_ids, + meta_info: TimedMetaInfo { + info: &response.meta_info, + timing: meta.timing.map(MetaInfoTiming::from), + }, + }) + .collect(); + axum::Json(timed).into_response() +} + +/// A `GenerateResponse` serialized with its sequence's timing added to `meta_info`. +#[derive(Serialize)] +struct TimedResponse<'a> { + text: &'a str, + output_ids: &'a [u32], + meta_info: TimedMetaInfo<'a>, +} + +#[derive(Serialize)] +struct TimedMetaInfo<'a> { + #[serde(flatten)] + info: &'a GenerateMetaInfo, + #[serde(flatten)] + timing: Option, } async fn collect_completes(mut stream: TokenHandle) -> Result, Response> { diff --git a/atom/mesh/src/routers/render/generate_streaming.rs b/atom/mesh/src/routers/render/generate_streaming.rs index 02a8f74b753..20244947af8 100644 --- a/atom/mesh/src/routers/render/generate_streaming.rs +++ b/atom/mesh/src/routers/render/generate_streaming.rs @@ -18,7 +18,7 @@ use crate::{ routers::{ prepare::response_context::{ProtocolRequest, ResponseContext}, render::{ - chat_streaming::process_chunk_tokens, + chat_streaming::{process_chunk_tokens, unstreamed}, logprob_conversion::{input_logprobs_to_generate, output_logprobs_to_generate}, }, token_handle::{ @@ -99,9 +99,12 @@ async fn run_generate_stream( let mut weight_version: Option = None; let mut prompt_tokens_seen: u32 = 0; let mut accumulated_output_logprobs: Option>>> = None; + let mut consumed = 0; while let Some(item) = stream.next().await { let chunk = item.map_err(engine_error_to_string)?; + // A Complete's ids past the partials' (SGLang's and vLLM's carries them all). + let rest = unstreamed(&chunk, consumed, usize::MAX); match chunk { TokenChunk::Partial { token_ids, @@ -111,9 +114,9 @@ async fn run_generate_stream( first_token_time = Some(Instant::now()); } completion_tokens += token_ids.len() as u32; + consumed += token_ids.len(); - // Decoded across chunks, as the unstreamed text is: a character - // split between two steps comes out whole. + // Decoded across chunks, as the unary text is, so a chunk boundary loses no text. let (chunk_text, _stopped) = process_chunk_tokens(&mut stop_decoder, &token_ids); accumulated_text.push_str(&chunk_text); @@ -144,7 +147,6 @@ async fn run_generate_stream( .map_err(|_| "send chunk".to_string())?; } TokenChunk::Complete { - token_ids, finish_reason, usage, meta, @@ -152,10 +154,15 @@ async fn run_generate_stream( input_logprobs, .. } => { + let rest = rest.unwrap_or_default(); + let (text, _stopped) = process_chunk_tokens(&mut stop_decoder, &rest); + accumulated_text.push_str(&text); if let SequenceDecoderOutput::Text(text) = stop_decoder.flush() { accumulated_text.push_str(&text); } prompt_tokens_seen = usage.prompt_tokens; + // The terminal count covers the ids the Complete carried past the partials. + completion_tokens = usage.completion_tokens; if weight_version.is_none() { weight_version = meta.weight_version.clone(); } @@ -176,15 +183,9 @@ async fn run_generate_stream( let e2e_latency = start_time.elapsed().as_secs_f64(); let fr = finish_reason_to_generate(&finish_reason, usage.completion_tokens); - let last = token_ids - .last() - .copied() - .map(|t| vec![t]) - .unwrap_or_default(); - let response = json!({ "text": accumulated_text.clone(), - "output_ids": last, + "output_ids": rest, "meta_info": { "id": index_id, "finish_reason": fr, diff --git a/atom/mesh/src/routers/render/tests.rs b/atom/mesh/src/routers/render/tests.rs index 78a5e8e8579..4facf7446f3 100644 --- a/atom/mesh/src/routers/render/tests.rs +++ b/atom/mesh/src/routers/render/tests.rs @@ -28,6 +28,8 @@ mod test_support { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -53,6 +55,8 @@ mod test_support { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } } @@ -186,7 +190,8 @@ mod b2_chat_aggregator_branches { use crate::routers::token_handle::engine_error::EngineError; use crate::routers::token_handle::test_support::synthetic_single_stream; use crate::routers::token_handle::token_chunk::{ - FinishReason, MatchedStop, TokenChunk, TokenLogprob, TokenLogprobs, Usage, WorkerMeta, + FinishReason, MatchedStop, SeqTiming, TokenChunk, TokenLogprob, TokenLogprobs, Usage, + WorkerMeta, }; use crate::tokenizer::{traits::Tokenizer, MockTokenizer}; @@ -217,6 +222,8 @@ mod b2_chat_aggregator_branches { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -515,6 +522,86 @@ mod b2_chat_aggregator_branches { assert!(s.contains("usage")); assert!(s.contains("\"total_tokens\":10")); } + + /// A sibling's Complete as an ATOM worker reports it when `timed`, with `cached` tokens. + fn sibling(timed: Option<(f64, f64, f64)>, cached: u32) -> TokenChunk { + let mut complete = cmpl(vec![1], FinishReason::Stop, None); + if let TokenChunk::Complete { meta, .. } = &mut complete { + meta.cached_tokens = cached; + meta.timing = timed.map(|(ttft_s, tpot_s, latency_s)| SeqTiming { + ttft: ttft_s, + tpot: tpot_s, + latency: latency_s, + }); + } + complete + } + + async fn usage_of(completes: Vec) -> serde_json::Value { + let stream = synthetic_single_stream(completes.into_iter().map(Ok).collect()); + let req = ChatCompletionRequest::default(); + let resp = chat_aggregator::process(stream, ctx_with(req)).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + json["usage"].clone() + } + + #[tokio::test] + async fn test_aggregator_usage_reports_atom_s_cached_tokens_and_timing() { + let usage = usage_of(vec![sibling(Some((0.123456, 0.01, 1.5)), 2)]).await; + let expected = serde_json::json!({ + "prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5, + "prompt_tokens_details": {"cached_tokens": 2}, + "ttft_s": 0.1235, "tpot_s": 0.01, "latency_s": 1.5, + }); + assert_eq!(usage, expected); + + // An SGLang or vLLM worker's usage keeps its shape. + let usage = usage_of(vec![sibling(None, 2)]).await; + let expected = serde_json::json!({ + "prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5, + }); + assert_eq!(usage, expected); + } + + #[tokio::test] + async fn test_aggregator_usage_of_atom_siblings_counts_the_prompt_once() { + let usage = usage_of(vec![ + sibling(Some((0.1, 0.02, 1.0)), 2), + sibling(Some((0.3, 0.01, 0.5)), 2), + ]) + .await; + // Cached tokens of the shared prompt once, the slowest timing, and n. + let expected = serde_json::json!({ + "prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7, + "prompt_tokens_details": {"cached_tokens": 2}, + "ttft_s": 0.3, "tpot_s": 0.02, "latency_s": 1.0, "num_choices": 2, + }); + assert_eq!(usage, expected); + } + + #[tokio::test] + async fn test_aggregator_reasoning_only_atom_output_carries_an_empty_content() { + for reads_as_atom in [true, false] { + let req = ChatCompletionRequest { + separate_reasoning: true, + ..Default::default() + }; + let mut ctx = ctx_with(req); + ctx.configured_reasoning_parser = Some("deepseek_r1".to_string()); + ctx.reads_as_atom = reads_as_atom; + let complete = cmpl(vec![1, 2], FinishReason::Length, None); + let stream = synthetic_single_stream(vec![Ok(complete)]); + let resp = chat_aggregator::process(stream, ctx).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let message = &json["choices"][0]["message"]; + assert_eq!(message["reasoning_content"], "Hello world"); + // ATOM's HTTP chat answers ""; SGLang's and vLLM's leave content out. + let content = message.get("content"); + assert_eq!(content, reads_as_atom.then_some(&serde_json::json!(""))); + } + } } mod b3_chat_aggregator_typed { @@ -556,6 +643,8 @@ mod b3_chat_aggregator_typed { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -916,7 +1005,8 @@ mod c2_chat_streaming_branches { use crate::routers::token_handle::engine_error::EngineError; use crate::routers::token_handle::test_support::synthetic_single_stream; use crate::routers::token_handle::token_chunk::{ - FinishReason, MatchedStop, TokenChunk, TokenLogprob, TokenLogprobs, Usage, WorkerMeta, + FinishReason, MatchedStop, SeqTiming, TokenChunk, TokenLogprob, TokenLogprobs, Usage, + WorkerMeta, }; use crate::tokenizer::{traits::Tokenizer, MockTokenizer}; @@ -969,6 +1059,8 @@ mod c2_chat_streaming_branches { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -1180,6 +1272,150 @@ mod c2_chat_streaming_branches { assert!(s.contains("\"total_tokens\":8") || s.contains("total_tokens")); } + /// The usage chunk of a stream whose Complete `timed` (an ATOM worker's) or not. + async fn usage_chunk(include_usage: bool, timed: bool) -> Option { + let mut req = ChatCompletionRequest::default(); + req.stream = true; + req.stream_options = include_usage.then_some(StreamOptions { + include_usage: Some(true), + }); + let mut meta = meta_plain(); + meta.cached_tokens = 2; + meta.timing = timed.then_some(SeqTiming { + ttft: 0.1, + tpot: 0.01, + latency: 1.0, + }); + let stream = synthetic_single_stream(vec![Ok(TokenChunk::Complete { + token_ids: vec![1], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: usage(3, 5), + logprobs: None, + input_logprobs: None, + meta, + })]); + let s = body_of(chat_streaming::process(stream, ctx_with(req), "regular")).await; + let mut events = s.lines().filter_map(|line| line.strip_prefix("data: ")); + let chunk = events.find(|e| e.contains("\"usage\""))?; + Some(serde_json::from_str(chunk).unwrap()) + } + + #[tokio::test] + async fn test_streaming_atom_usage_chunk_ends_every_stream_with_the_cached_tokens() { + // After the finish chunk, as ATOM's HTTP chat_finish_frames sends it. + for include_usage in [false, true] { + let chunk = usage_chunk(include_usage, true) + .await + .expect("a usage chunk"); + assert_eq!(chunk["choices"], serde_json::json!([])); + let expected = serde_json::json!({ + "prompt_tokens": 3, "completion_tokens": 5, "total_tokens": 8, + "prompt_tokens_details": {"cached_tokens": 2}, + }); + assert_eq!(chunk["usage"], expected); + } + // An SGLang or vLLM stream keeps its opt-in usage chunk, without the cached tokens. + assert!(usage_chunk(false, false).await.is_none()); + let chunk = usage_chunk(true, false).await.expect("a usage chunk"); + assert!(chunk["usage"].get("prompt_tokens_details").is_none()); + } + + /// The data events of an ATOM worker's stream whose usage rides on its finish chunk. + async fn usage_on_finish_events(include_usage: bool) -> Vec { + let req = ChatCompletionRequest { + stream: true, + stream_options: include_usage.then_some(StreamOptions { + include_usage: Some(true), + }), + ..Default::default() + }; + let mut meta = meta_plain(); + meta.cached_tokens = 2; + meta.timing = Some(SeqTiming { + ttft: 0.1, + tpot: 0.01, + latency: 1.0, + }); + let stream = synthetic_single_stream(vec![Ok(TokenChunk::Complete { + token_ids: vec![1], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: usage(3, 5), + logprobs: None, + input_logprobs: None, + meta, + })]); + let mut ctx = ctx_with(req); + ctx.reads_as_atom = true; + ctx.usage_on_finish = true; + let s = body_of(chat_streaming::process(stream, ctx, "regular")).await; + s.lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter(|event| *event != "[DONE]") + .map(|event| serde_json::from_str(event).unwrap()) + .collect() + } + + #[tokio::test] + async fn test_streaming_atom_usage_rides_on_the_finish_chunk_where_its_worker_puts_it() { + // As ATOM's HTTP chat_finish_frames with usage_on_finish (DeepSeek-V4.1's contract). + for include_usage in [false, true] { + let events = usage_on_finish_events(include_usage).await; + let (finish, before) = events.split_last().unwrap(); + assert_eq!(finish["choices"][0]["finish_reason"], "stop"); + let expected = serde_json::json!({ + "prompt_tokens": 3, "completion_tokens": 5, "total_tokens": 8, + "prompt_tokens_details": {"cached_tokens": 2}, + }); + assert_eq!(finish["usage"], expected); + assert!(before.len() >= 2, "{before:?}"); + for event in before { + // include_usage adds `usage: null` to every chunk before the finish chunk. + assert_eq!( + event.get("usage"), + include_usage.then_some(&serde_json::Value::Null) + ); + } + } + } + + /// The first event of a stream whose only output decodes to no text. + async fn first_event_without_text(reads_as_atom: bool) -> serde_json::Value { + let mut req = ChatCompletionRequest::default(); + req.stream = true; + let stream = synthetic_single_stream(vec![ + Ok(TokenChunk::Partial { + token_ids: vec![999], // , which decodes to no text + logprobs: None, + }), + Ok(TokenChunk::Complete { + token_ids: vec![], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: usage(3, 1), + logprobs: None, + input_logprobs: None, + meta: meta_plain(), + }), + ]); + let mut ctx = ctx_with(req); + ctx.reads_as_atom = reads_as_atom; + let s = body_of(chat_streaming::process(stream, ctx, "regular")).await; + let mut events = s.lines().filter_map(|line| line.strip_prefix("data: ")); + serde_json::from_str(events.next().unwrap()).unwrap() + } + + #[tokio::test] + async fn test_streaming_atom_output_without_text_opens_with_an_empty_content() { + let json = first_event_without_text(true).await; + assert_eq!(json["choices"][0]["delta"]["role"], "assistant"); + assert_eq!(json["choices"][0]["delta"]["content"], ""); + // SGLang's and vLLM's streams open with their first text. + let json = first_event_without_text(false).await; + assert_eq!(json["choices"][0]["finish_reason"], "stop"); + } + #[tokio::test] async fn test_streaming_weight_version_threaded_as_system_fingerprint() { let stream = synthetic_single_stream(vec![Ok(TokenChunk::Complete { @@ -1335,6 +1571,8 @@ mod c3_chat_streaming_parsers { configured_tool_parser: configured_tool.map(|s| s.to_string()), configured_reasoning_parser: configured_reasoning.map(|s| s.to_string()), prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -1544,6 +1782,8 @@ mod c4_chat_streaming_coverage { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -1566,6 +1806,8 @@ mod c4_chat_streaming_coverage { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -1587,6 +1829,8 @@ mod c4_chat_streaming_coverage { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -2211,6 +2455,8 @@ mod c4_chat_streaming_coverage { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, }; let stream = synthetic_single_stream(vec![ Ok(TokenChunk::Partial { @@ -2707,6 +2953,51 @@ mod d_generate_aggregator { assert!(s.contains("meta_info"), "got: {s}"); } + /// An ATOM worker's timed reply is the response with its timing keys appended to + /// `meta_info`, byte for byte. + #[tokio::test] + async fn test_generate_aggregator_appends_atom_s_timing_to_meta_info() { + use crate::routers::token_handle::token_chunk::SeqTiming; + let mut timed = meta(); + timed.timing = Some(SeqTiming { + ttft: 0.1, + tpot: 0.01, + latency: 1.0, + }); + let stream = synthetic_single_stream(vec![Ok(TokenChunk::Complete { + token_ids: vec![10, 20], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 1, + completion_tokens: 2, + total_tokens: 3, + }, + logprobs: None, + input_logprobs: None, + meta: timed, + })]); + let resp = generate_aggregator::process(stream, generate_ctx()).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let got: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let info = &got[0]["meta_info"]; + let expected = serde_json::json!([{ + "text": got[0]["text"], + "output_ids": [10, 20], + "meta_info": { + "id": info["id"], + "finish_reason": {"type": "stop"}, + "prompt_tokens": 1, + "weight_version": "default", + "completion_tokens": 2, + "cached_tokens": 0, + "e2e_latency": info["e2e_latency"], + "ttft_s": 0.1, "tpot_s": 0.01, "latency_s": 1.0, + }, + }]); + assert_eq!(body, serde_json::to_vec(&expected).unwrap()); + } + #[tokio::test] async fn test_generate_aggregator_propagates_engine_error() { use crate::routers::token_handle::engine_error::EngineError; @@ -2990,6 +3281,8 @@ mod d2_generate_aggregator_branches { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, }; let stream = synthetic_single_stream(vec![Ok(TokenChunk::Complete { token_ids: vec![1, 2, 3], @@ -3037,6 +3330,8 @@ mod d2_generate_aggregator_branches { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, }; let lp = TokenLogprobs { items: vec![TokenLogprob { @@ -3363,6 +3658,47 @@ mod e1_generate_streaming_body_content { assert!(s.contains("[DONE]")); } + /// The final event carries every id the partials did not, whatever a Complete + /// carries. + #[tokio::test] + async fn test_generate_streaming_final_event_carries_every_unstreamed_id() { + let complete = |token_ids: Vec| TokenChunk::Complete { + token_ids, + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage::default(), + logprobs: None, + input_logprobs: None, + meta: meta(), + }; + let partial = TokenChunk::Partial { + token_ids: vec![1], + logprobs: None, + }; + for (chunks, ids) in [ + ( + vec![partial, complete(vec![1, 2, 6])], + vec![vec![1], vec![2, 6]], + ), + (vec![complete(vec![1, 2, 6])], vec![vec![1, 2, 6]]), + ] { + let stream = synthetic_single_stream(chunks.into_iter().map(Ok).collect()); + let body = body_of(generate_streaming::process( + stream, + generate_ctx(), + "regular", + )); + let events: Vec> = body + .await + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter_map(|data| serde_json::from_str::(data).ok()) + .map(|event| serde_json::from_value(event["output_ids"].clone()).unwrap()) + .collect(); + assert_eq!(events, ids); + } + } + #[tokio::test] async fn test_generate_streaming_complete_emits_e2e_latency() { let stream = synthetic_single_stream(vec![Ok(TokenChunk::Complete { @@ -3498,6 +3834,8 @@ mod e2_generate_streaming_branches { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -3733,6 +4071,998 @@ mod e2_generate_streaming_branches { } } +/// Streaming metrics count the output a Complete carries past the partials too. +mod e4_generate_streaming_output_tokens { + use axum::body::to_bytes; + + use super::test_support::generate_ctx; + use crate::routers::render::generate_streaming; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}; + + #[tokio::test] + async fn test_output_tokens_are_the_complete_s_count() { + let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder(); + let handle = recorder.handle(); + let _recorder = metrics::set_default_local_recorder(&recorder); + let partial = |id| { + Ok(TokenChunk::Partial { + token_ids: vec![id], + logprobs: None, + }) + }; + let complete = Ok(TokenChunk::Complete { + token_ids: vec![1, 2, 3], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 1, + completion_tokens: 3, + total_tokens: 4, + }, + logprobs: None, + input_logprobs: None, + meta: WorkerMeta::default(), + }); + let stream = synthetic_single_stream(vec![partial(1), partial(2), complete]); + let resp = generate_streaming::process(stream, generate_ctx(), "regular"); + to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let rendered = handle.render(); + let output = rendered + .lines() + .find(|line| { + line.starts_with("mesh_router_tokens_total{") + && line.contains("token_type=\"output\"") + }) + .and_then(|line| line.rsplit_once(' ')?.1.parse::().ok()); + assert_eq!(output, Some(3.0), "{rendered}"); + } +} + +mod e3_generate_streaming_across_chunks { + use std::sync::Arc; + + use axum::body::to_bytes; + use axum::response::Response; + use serde_json::Value; + use tempfile::TempDir; + + use super::test_support::generate_ctx; + use crate::routers::grpc::completion_adapter::wrap_streaming_generate_as_completion; + use crate::routers::prepare::response_context::ResponseContext; + use crate::routers::prepare::stop_decoder_builder::create_stop_decoder; + use crate::routers::render::{generate_aggregator, generate_streaming}; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}; + use crate::routers::token_handle::token_handle::TokenHandle; + use crate::tokenizer::{huggingface::HuggingFaceTokenizer, traits::Tokenizer}; + + /// DeepSeek-V4.1-Flash's decoder and its vocabulary entries for the ids in `CASES`. + const TOKENIZER_JSON: &str = r#"{ + "version": "1.0", + "truncation": null, + "padding": null, + "added_tokens": [], + "normalizer": null, + "pre_tokenizer": null, + "post_processor": null, + "decoder": { + "type": "ByteLevel", "add_prefix_space": true, "trim_offsets": true, "use_regex": true + }, + "model": { + "type": "BPE", + "vocab": { + "ä»ĸåĢij": 9281, "說": 4172, "ï¼ļ": 768, "鬱": 89474, "èĶ": 6355, "¥": 101, + "çļĦ": 301, "é¾": 2715, "ĺ": 249, "ðŁĺ": 28927, "Ģ": 225, "ðŁijį": 92526, + "ðŁı": 40965, "½": 124, "Ġem": 980, "oji": 82644 + }, + "merges": [] + } + }"#; + + /// Each string and its DeepSeek-V4.1-Flash ids; some ids decode alone to part of a character. + const CASES: [(&str, &[u32]); 2] = [ + ( + "他們說:鬱鬱蔥蔥的龘", + &[ + 9281, 4172, 768, 89474, 89474, 6355, 101, 6355, 101, 301, 2715, 249, + ], + ), + ("😀👍🏽 emoji", &[28927, 225, 92526, 40965, 124, 980, 82644]), + ]; + + fn tokenizer() -> Arc { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("tokenizer.json"); + std::fs::write(&path, TOKENIZER_JSON).unwrap(); + Arc::new(HuggingFaceTokenizer::from_file(path.to_str().unwrap()).unwrap()) + } + + fn ctx(tokenizer: &Arc) -> ResponseContext { + ResponseContext { + tokenizer: tokenizer.clone(), + stop_decoder: create_stop_decoder(tokenizer, None, None, true, false), + ..generate_ctx() + } + } + + fn complete(token_ids: Vec, completion_tokens: u32) -> TokenChunk { + TokenChunk::Complete { + token_ids, + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 1, + completion_tokens, + total_tokens: 1 + completion_tokens, + }, + logprobs: None, + input_logprobs: None, + meta: WorkerMeta { + request_id: "req".to_string(), + weight_version: None, + cached_tokens: 0, + timing: None, + }, + } + } + + /// One id a chunk, then the Complete ATOM ends a stream with, which carries no ids. + fn token_by_token(ids: &[u32]) -> TokenHandle { + let mut chunks: Vec<_> = ids + .iter() + .map(|&id| { + Ok(TokenChunk::Partial { + token_ids: vec![id], + logprobs: None, + }) + }) + .collect(); + chunks.push(Ok(complete(Vec::new(), ids.len() as u32))); + synthetic_single_stream(chunks) + } + + async fn data_events(resp: Response) -> Vec { + let body = to_bytes(resp.into_body(), 256 * 1024).await.unwrap(); + std::str::from_utf8(&body) + .unwrap() + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter(|data| *data != "[DONE]") + .map(|data| serde_json::from_str(data).unwrap()) + .collect() + } + + #[tokio::test] + async fn test_generate_and_completions_streams_token_by_token_join_to_the_unary_text() { + let tokenizer = tokenizer(); + for (text, ids) in CASES { + let whole = synthetic_single_stream(vec![Ok(complete(ids.to_vec(), ids.len() as u32))]); + let resp = generate_aggregator::process(whole, ctx(&tokenizer)).await; + let body = to_bytes(resp.into_body(), 256 * 1024).await.unwrap(); + let unary: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(unary[0]["text"], text); + + let resp = generate_streaming::process(token_by_token(ids), ctx(&tokenizer), "regular"); + let events = data_events(resp).await; + assert_eq!(events.last().unwrap()["text"], text); + + let resp = generate_streaming::process(token_by_token(ids), ctx(&tokenizer), "regular"); + let completion = wrap_streaming_generate_as_completion(resp, "m".into()).await; + let events = data_events(completion).await; + let pieces = events + .iter() + .filter_map(|e| e["choices"][0]["text"].as_str()); + assert_eq!(pieces.collect::(), text); + } + } +} + +mod f_atom_reasoning_opener { + use std::sync::Arc; + + use axum::body::to_bytes; + use serde_json::Value; + + use crate::protocols::chat::ChatCompletionRequest; + use crate::routers::prepare::response_context::{ProtocolRequest, ResponseContext}; + use crate::routers::prepare::stop_decoder_builder::create_stop_decoder; + use crate::routers::render::{chat_aggregator, chat_streaming}; + use crate::routers::test_mocks; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}; + use crate::tokenizer::{huggingface::HuggingFaceTokenizer, traits::Tokenizer}; + + /// A byte-level BPE, which encodes any text. + fn tokenizer() -> Arc { + let dir = + test_mocks::tokenizer::byte_level_tokenizer_dir(&[], false, serde_json::json!({})); + let path = dir.path().join("tokenizer.json"); + Arc::new(HuggingFaceTokenizer::from_file(path.to_str().unwrap()).unwrap()) + } + + /// A chat whose reply is read with qwen3, which starts outside reasoning, after + /// `opener`, the prompt's. + fn ctx(stream: bool, opener: Option<&str>) -> ResponseContext { + let tokenizer = tokenizer(); + let stop_decoder = create_stop_decoder(&tokenizer, None, None, true, false); + let req = ChatCompletionRequest { + stream, + separate_reasoning: true, + ..Default::default() + }; + ResponseContext { + original: ProtocolRequest::Chat(Arc::new(req)), + model_id: Some("m".to_string()), + headers: None, + original_text: None, + processed_messages: None, + tokenizer, + stop_decoder, + request_id: "rid".to_string(), + created: 0, + tool_parser_factory: None, + reasoning_parser_factory: Some(test_mocks::reasoning_parser_factory()), + configured_tool_parser: None, + configured_reasoning_parser: Some("qwen3".to_string()), + prompt_opener: opener.map(str::to_string), + reads_as_atom: false, + usage_on_finish: false, + } + } + + /// `reply`'s ids, streamed one at a time when `partials`, then its Complete. + fn chunks(reply: &str, partials: bool) -> Vec { + let ids = tokenizer() + .encode(reply, false) + .unwrap() + .token_ids() + .to_vec(); + let mut chunks: Vec = Vec::new(); + if partials { + chunks.extend(ids.iter().map(|&id| TokenChunk::Partial { + token_ids: vec![id], + logprobs: None, + })); + } + chunks.push(TokenChunk::Complete { + token_ids: if partials { Vec::new() } else { ids.clone() }, + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 1, + completion_tokens: ids.len() as u32, + total_tokens: 1 + ids.len() as u32, + }, + logprobs: None, + input_logprobs: None, + meta: WorkerMeta::default(), + }); + chunks + } + + /// (reasoning, content) of `reply` answered unary. + async fn unary(reply: &str, opener: Option<&str>) -> (String, String) { + let stream = synthetic_single_stream(chunks(reply, false).into_iter().map(Ok).collect()); + let resp = chat_aggregator::process(stream, ctx(false, opener)).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let json: Value = serde_json::from_slice(&body).unwrap(); + let message = &json["choices"][0]["message"]; + let text = |key: &str| message[key].as_str().unwrap_or_default().to_string(); + (text("reasoning_content"), text("content")) + } + + /// (reasoning, content) of `reply` streamed, its deltas joined. + async fn streamed(reply: &str, opener: Option<&str>) -> (String, String) { + let stream = synthetic_single_stream(chunks(reply, true).into_iter().map(Ok).collect()); + let resp = chat_streaming::process(stream, ctx(true, opener), "regular"); + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let (mut reasoning, mut content) = (String::new(), String::new()); + for line in String::from_utf8_lossy(&body).lines() { + let Some(data) = line.strip_prefix("data: ") else { + continue; + }; + let Ok(event) = serde_json::from_str::(data) else { + continue; + }; + let delta = &event["choices"][0]["delta"]; + reasoning.push_str(delta["reasoning_content"].as_str().unwrap_or_default()); + content.push_str(delta["content"].as_str().unwrap_or_default()); + } + (reasoning, content) + } + + #[tokio::test] + async fn a_reply_to_a_prompt_that_closed_reasoning_is_content() { + // A thinking-off prompt ends in "": no opener. + let expected = (String::new(), "Hello world".to_string()); + assert_eq!(unary("Hello world", None).await, expected); + assert_eq!(streamed("Hello world", None).await, expected); + } + + #[tokio::test] + async fn a_reply_to_a_prompt_that_opened_reasoning_is_reasoning_up_to_its_closer() { + let reply = "plan itThe answer"; + let expected = ("plan it".to_string(), "The answer".to_string()); + assert_eq!(unary(reply, Some("")).await, expected); + let (reasoning, content) = streamed(reply, Some("")).await; + assert_eq!( + (reasoning.trim(), content.trim()), + ("plan it", "The answer") + ); + + // Cut before its closer, it is reasoning all through. + let expected = ("still planning".to_string(), String::new()); + assert_eq!(unary("still planning", Some("")).await, expected); + assert_eq!(streamed("still planning", Some("")).await, expected); + } + + /// Replayed 256 ids at a time, among them a reply whose closer the 256th id cuts + /// after its "<". + #[tokio::test] + async fn a_long_reply_arriving_in_its_complete_alone_is_split_as_when_streamed() { + for thought in ["z".repeat(70_000), "z".repeat(248)] { + let reply = format!("{thought}answer"); + let ids = tokenizer() + .encode(&reply, false) + .unwrap() + .token_ids() + .to_vec(); + let complete = chunks(&reply, false); + let stream = synthetic_single_stream(complete.into_iter().map(Ok).collect()); + let resp = chat_streaming::process(stream, ctx(true, None), "regular"); + let body = to_bytes(resp.into_body(), 1 << 20).await.unwrap(); + let (mut reasoning, mut content) = (String::new(), String::new()); + for line in String::from_utf8_lossy(&body).lines() { + let Some(event) = line + .strip_prefix("data: ") + .and_then(|data| serde_json::from_str::(data).ok()) + else { + continue; + }; + let delta = &event["choices"][0]["delta"]; + reasoning.push_str(delta["reasoning_content"].as_str().unwrap_or_default()); + content.push_str(delta["content"].as_str().unwrap_or_default()); + } + assert!(ids.len() > 256); + assert_eq!( + (reasoning.len(), content.as_str()), + (thought.len(), "answer") + ); + } + } + + #[tokio::test] + async fn a_streamed_reply_ending_in_a_delimiter_s_first_characters_keeps_them() { + // Ended inside reasoning on "<", or in content on "")).await, expected); + let expected = ("plan".to_string(), "3 3 ")).await, + expected + ); + } +} + +mod g_complete_suffix { + use axum::body::to_bytes; + use serde_json::Value; + + use super::test_support::{chat_ctx, generate_ctx}; + use crate::routers::render::{ + chat_aggregator, chat_streaming, generate_aggregator, generate_streaming, + }; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}; + + /// SGLang's or vLLM's stream: "Hello", "world", then a Complete with every id, its + /// last ("." , not an end of sequence) in no partial. + fn chunks(streamed: bool) -> Vec { + let partial = |id| TokenChunk::Partial { + token_ids: vec![id], + logprobs: None, + }; + let complete = TokenChunk::Complete { + token_ids: vec![1, 2, 6], + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage { + prompt_tokens: 1, + completion_tokens: 3, + total_tokens: 4, + }, + logprobs: None, + input_logprobs: None, + meta: WorkerMeta::default(), + }; + let mut chunks = if streamed { + vec![partial(1), partial(2)] + } else { + vec![] + }; + chunks.push(complete); + chunks + } + + async fn body(resp: axum::response::Response) -> String { + let bytes = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + String::from_utf8(bytes.to_vec()).unwrap() + } + + fn events(sse: &str) -> Vec { + sse.lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter_map(|data| serde_json::from_str(data).ok()) + .collect() + } + + #[tokio::test] + async fn a_streamed_chat_carries_the_complete_s_unstreamed_ids_as_unary_does() { + let stream = synthetic_single_stream(chunks(false).into_iter().map(Ok).collect()); + let unary: Value = + serde_json::from_str(&body(chat_aggregator::process(stream, chat_ctx()).await).await) + .unwrap(); + let mut ctx = chat_ctx(); + if let crate::routers::prepare::response_context::ProtocolRequest::Chat(req) = + &mut ctx.original + { + std::sync::Arc::make_mut(req).stream = true; + } + let stream = synthetic_single_stream(chunks(true).into_iter().map(Ok).collect()); + let sse = body(chat_streaming::process(stream, ctx, "regular")).await; + let streamed: String = events(&sse) + .iter() + .filter_map(|e| e["choices"][0]["delta"]["content"].as_str()) + .collect(); + assert_eq!(streamed, unary["choices"][0]["message"]["content"]); + assert!(streamed.ends_with('.'), "{streamed}"); + } + + /// The unstreamed id's delta carries its logprob from the Complete's, which covers every id. + #[tokio::test] + async fn a_streamed_chat_carries_the_logprobs_of_the_complete_s_unstreamed_ids() { + use crate::routers::token_handle::token_chunk::{TokenLogprob, TokenLogprobs}; + let logprob = |token_id, logprob| TokenLogprob { + token_id, + logprob, + decoded_text: None, + top: vec![], + }; + let mut chunks = chunks(true); + for (chunk, id) in chunks.iter_mut().zip([1, 2]) { + if let TokenChunk::Partial { logprobs, .. } = chunk { + *logprobs = Some(TokenLogprobs { + items: vec![logprob(id, -0.5)], + }); + } + } + if let Some(TokenChunk::Complete { logprobs, .. }) = chunks.last_mut() { + let items = vec![logprob(1, -0.5), logprob(2, -0.5), logprob(6, -0.25)]; + *logprobs = Some(TokenLogprobs { items }); + } + let mut ctx = chat_ctx(); + if let crate::routers::prepare::response_context::ProtocolRequest::Chat(req) = + &mut ctx.original + { + std::sync::Arc::make_mut(req).stream = true; + } + let stream = synthetic_single_stream(chunks.into_iter().map(Ok).collect()); + let sse = body(chat_streaming::process(stream, ctx, "regular")).await; + let last = events(&sse) + .into_iter() + .rfind(|e| e["choices"][0]["delta"]["content"] == " .") + .unwrap_or_else(|| panic!("no delta for the unstreamed id: {sse}")); + let logprobs = &last["choices"][0]["logprobs"]["content"]; + assert_eq!(logprobs[0]["logprob"], -0.25, "{last}"); + } + + #[tokio::test] + async fn a_streamed_generate_carries_the_complete_s_unstreamed_ids_as_unary_does() { + let stream = synthetic_single_stream(chunks(false).into_iter().map(Ok).collect()); + let unary: Value = serde_json::from_str( + &body(generate_aggregator::process(stream, generate_ctx()).await).await, + ) + .unwrap(); + let stream = synthetic_single_stream(chunks(true).into_iter().map(Ok).collect()); + let sse = body(generate_streaming::process( + stream, + generate_ctx(), + "regular", + )) + .await; + let last = events(&sse).pop().unwrap(); + assert_eq!(last["text"], unary[0]["text"]); + assert!(last["text"].as_str().unwrap().ends_with('.'), "{last}"); + } + + /// A streamed chat replays a long Complete 256 ids at a time, each piece copied + /// alone rather than cut from a copy of the whole remaining suffix. + #[test] + fn a_replayed_piece_copies_only_its_own_ids() { + use crate::routers::token_handle::token_chunk::{TokenLogprob, TokenLogprobs}; + let ids: Vec = (0..65_536).collect(); + let item = TokenLogprob { + token_id: 0, + logprob: -1.0, + decoded_text: None, + top: Vec::new(), + }; + let complete = TokenChunk::Complete { + token_ids: ids.clone(), + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage::default(), + logprobs: Some(TokenLogprobs { + items: vec![item; ids.len()], + }), + input_logprobs: None, + meta: WorkerMeta::default(), + }; + let piece = chat_streaming::unstreamed(&complete, 1024, 256).unwrap(); + assert_eq!((piece[0], piece.len(), piece.capacity()), (1024, 256, 256)); + let logprobs = chat_streaming::unstreamed_logprobs(&complete, 1024, 256).unwrap(); + assert_eq!( + (logprobs.items.len(), logprobs.items.capacity()), + (256, 256) + ); + let whole = chat_streaming::unstreamed(&complete, 1024, usize::MAX).unwrap(); + assert_eq!(whole.len(), 65_536 - 1024); // /generate's whole suffix + } +} + +mod h_atom_native_tool_calls { + use std::sync::Arc; + + use axum::body::to_bytes; + use serde_json::{json, Value}; + + use crate::protocols::chat::ChatCompletionRequest; + use crate::routers::prepare::response_context::{ProtocolRequest, ResponseContext}; + use crate::routers::prepare::stop_decoder_builder::create_stop_decoder; + use crate::routers::render::{chat_aggregator, chat_streaming}; + use crate::routers::test_mocks; + use crate::routers::token_handle::test_support::synthetic_single_stream; + use crate::routers::token_handle::token_chunk::{FinishReason, TokenChunk, Usage, WorkerMeta}; + use crate::tokenizer::{huggingface::HuggingFaceTokenizer, traits::Tokenizer}; + + const CALL: &str = + "\n{\"name\": \"get_weather\", \"arguments\": {\"city\": \"Paris\"}}\n"; + + fn tokenizer() -> Arc { + let dir = test_mocks::tokenizer::byte_level_tokenizer_dir(&[], false, json!({})); + let path = dir.path().join("tokenizer.json"); + Arc::new(HuggingFaceTokenizer::from_file(path.to_str().unwrap()).unwrap()) + } + + /// An ATOM reply in qwen's tool syntax to a chat forcing `choice`. + fn ctx(stream: bool, choice: Value) -> ResponseContext { + let tokenizer = tokenizer(); + let tool = + json!({"type": "function", "function": {"name": "get_weather", "parameters": {}}}); + let req: ChatCompletionRequest = serde_json::from_value(json!({ + "model": "m", "messages": [{"role": "user", "content": "hi"}], + "tools": [tool], "tool_choice": choice, "stream": stream, + })) + .unwrap(); + ResponseContext { + original: ProtocolRequest::Chat(Arc::new(req)), + model_id: Some("m".to_string()), + headers: None, + original_text: None, + processed_messages: None, + stop_decoder: create_stop_decoder(&tokenizer, None, None, false, false), + tokenizer, + request_id: "rid".to_string(), + created: 0, + tool_parser_factory: Some(test_mocks::tool_parser_factory()), + reasoning_parser_factory: None, + configured_tool_parser: Some("qwen".to_string()), + configured_reasoning_parser: None, + prompt_opener: None, + reads_as_atom: true, + usage_on_finish: false, + } + } + + fn chunks(streamed: bool) -> Vec { + let ids = tokenizer() + .encode(CALL, false) + .unwrap() + .token_ids() + .to_vec(); + let mut chunks: Vec = Vec::new(); + if streamed { + chunks.extend(ids.chunks(4).map(|ids| TokenChunk::Partial { + token_ids: ids.to_vec(), + logprobs: None, + })); + } + chunks.push(TokenChunk::Complete { + token_ids: if streamed { Vec::new() } else { ids }, + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage::default(), + logprobs: None, + input_logprobs: None, + meta: WorkerMeta::default(), + }); + chunks + } + + fn forced_choices() -> [Value; 2] { + [ + json!({"type": "function", "function": {"name": "get_weather"}}), + json!("required"), + ] + } + + #[tokio::test] + async fn a_forced_atom_tool_call_is_parsed_in_the_model_s_syntax() { + for choice in forced_choices() { + let stream = synthetic_single_stream(chunks(false).into_iter().map(Ok).collect()); + let resp = chat_aggregator::process(stream, ctx(false, choice.clone())).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let json: Value = serde_json::from_slice(&body).unwrap(); + let call = &json["choices"][0]["message"]["tool_calls"][0]["function"]; + assert_eq!(call["name"], "get_weather", "{choice}: {json}"); + let arguments: Value = + serde_json::from_str(call["arguments"].as_str().unwrap()).unwrap(); + assert_eq!(arguments, json!({"city": "Paris"})); + } + } + + /// The declared schema types the unary reply's arguments, as it does the streamed one's. + #[tokio::test] + async fn a_unary_tool_call_keeps_a_string_declared_argument_a_string() { + let tool = json!({"type": "function", "function": {"name": "search", "parameters": { + "type": "object", "properties": {"limit": {"type": "string"}}, + }}}); + let req: ChatCompletionRequest = serde_json::from_value(json!({ + "model": "m", "messages": [{"role": "user", "content": "hi"}], "tools": [tool], + })) + .unwrap(); + let mut ctx = ctx(false, json!("auto")); + ctx.original = ProtocolRequest::Chat(Arc::new(req)); + ctx.configured_tool_parser = Some("qwen_xml".to_string()); + let call = + "4"; + let ids = tokenizer() + .encode(call, false) + .unwrap() + .token_ids() + .to_vec(); + let stream = synthetic_single_stream(vec![Ok(TokenChunk::Complete { + token_ids: ids, + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage::default(), + logprobs: None, + input_logprobs: None, + meta: WorkerMeta::default(), + })]); + let resp = chat_aggregator::process(stream, ctx).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let json: Value = serde_json::from_slice(&body).unwrap(); + let call = &json["choices"][0]["message"]["tool_calls"][0]["function"]; + let arguments: Value = serde_json::from_str(call["arguments"].as_str().unwrap()).unwrap(); + assert_eq!(arguments, json!({"limit": "4"}), "{json}"); + } + + #[tokio::test] + async fn a_forced_atom_tool_call_streams_in_the_model_s_syntax() { + for choice in forced_choices() { + let stream = synthetic_single_stream(chunks(true).into_iter().map(Ok).collect()); + let resp = chat_streaming::process(stream, ctx(true, choice.clone()), "regular"); + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let (mut name, mut arguments) = (String::new(), String::new()); + for line in String::from_utf8_lossy(&body).lines() { + let Some(event) = line + .strip_prefix("data: ") + .and_then(|data| serde_json::from_str::(data).ok()) + else { + continue; + }; + for call in event["choices"][0]["delta"]["tool_calls"] + .as_array() + .into_iter() + .flatten() + { + name.push_str(call["function"]["name"].as_str().unwrap_or_default()); + arguments.push_str(call["function"]["arguments"].as_str().unwrap_or_default()); + } + } + assert_eq!(name, "get_weather", "{choice}"); + let arguments: Value = serde_json::from_str(&arguments).unwrap(); + assert_eq!(arguments, json!({"city": "Paris"}), "{choice}"); + } + } + + /// A qwen_xml reply cut off by max_tokens inside a call: (name, arguments) of the call + /// read unary, then streamed. + async fn cut_off_call(reply: &str) -> [(String, Value); 2] { + cut_off_call_reasoned(reply, None).await + } + + /// `cut_off_call`, its reasoning separated by the `reasoning` parser. + async fn cut_off_call_reasoned(reply: &str, reasoning: Option<&str>) -> [(String, Value); 2] { + cut_off_call_with(reply, "qwen_xml", reasoning).await + } + + /// `cut_off_call_reasoned`, its tool calls read by `parser`. + async fn cut_off_call_with( + reply: &str, + parser: &str, + reasoning: Option<&str>, + ) -> [(String, Value); 2] { + let tool = json!({"type": "function", "function": {"name": "get_weather", "parameters": { + "type": "object", "properties": {"city": {"type": "string"}}, + }}}); + let ids = tokenizer() + .encode(reply, false) + .unwrap() + .token_ids() + .to_vec(); + let mut read = Vec::new(); + for stream in [false, true] { + let req: ChatCompletionRequest = serde_json::from_value(json!({ + "model": "m", "messages": [{"role": "user", "content": "hi"}], + "tools": [tool.clone()], "stream": stream, + })) + .unwrap(); + let mut ctx = ctx(stream, json!("auto")); + ctx.original = ProtocolRequest::Chat(Arc::new(req)); + ctx.configured_tool_parser = Some(parser.to_string()); + if let Some(parser) = reasoning { + ctx.reasoning_parser_factory = Some(test_mocks::reasoning_parser_factory()); + ctx.configured_reasoning_parser = Some(parser.to_string()); + } + let mut chunks: Vec = Vec::new(); + if stream { + chunks.extend(ids.chunks(3).map(|ids| TokenChunk::Partial { + token_ids: ids.to_vec(), + logprobs: None, + })); + } + chunks.push(TokenChunk::Complete { + token_ids: if stream { Vec::new() } else { ids.clone() }, + finish_reason: FinishReason::Length, + matched_stop: None, + usage: Usage::default(), + logprobs: None, + input_logprobs: None, + meta: WorkerMeta::default(), + }); + let stream_of = synthetic_single_stream(chunks.into_iter().map(Ok).collect()); + let (mut name, mut arguments) = (String::new(), String::new()); + if stream { + let resp = chat_streaming::process(stream_of, ctx, "regular"); + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + for line in String::from_utf8_lossy(&body).lines() { + let Some(event) = line + .strip_prefix("data: ") + .and_then(|data| serde_json::from_str::(data).ok()) + else { + continue; + }; + let calls = event["choices"][0]["delta"]["tool_calls"] + .as_array() + .cloned(); + for call in calls.into_iter().flatten() { + name.push_str(call["function"]["name"].as_str().unwrap_or_default()); + let delta = call["function"]["arguments"].as_str().unwrap_or_default(); + arguments.push_str(delta); + } + } + } else { + let resp = chat_aggregator::process(stream_of, ctx).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let json: Value = serde_json::from_slice(&body).unwrap(); + let call = &json["choices"][0]["message"]["tool_calls"][0]["function"]; + name.push_str(call["name"].as_str().unwrap_or_default()); + arguments.push_str(call["arguments"].as_str().unwrap_or_default()); + } + let arguments = serde_json::from_str(&arguments).unwrap_or(Value::Null); + read.push((name, arguments)); + } + read.try_into().unwrap() + } + + #[tokio::test] + async fn a_native_call_cut_off_by_max_tokens_keeps_its_arrived_value() { + let reply = "Paris"; + let expected = ("get_weather".to_string(), json!({"city": "Paris"})); + assert_eq!(cut_off_call(reply).await, [expected.clone(), expected]); + // Prose quoting the syntax is not a call. + let prose = "You write and then its parameters"; + let none = (String::new(), Value::Null); + assert_eq!(cut_off_call(prose).await, [none.clone(), none]); + } + + /// A last "<" the reasoning parser holds until the Complete releases it still reaches + /// the call it ends, streamed as unary. + #[tokio::test] + async fn a_cut_off_call_keeps_a_last_character_the_reasoning_parser_held() { + let reply = "Paris<"; + let expected = ("get_weather".to_string(), json!({"city": "Paris<"})); + let read = cut_off_call_reasoned(reply, Some("qwen3")).await; + assert_eq!(read, [expected.clone(), expected]); + } + + /// A qwen_xml call cut off after its function closed but before its wrapper did is + /// kept, as ATOM's HTTP parser keeps it; a name prose follows is not closed as one. + #[tokio::test] + async fn a_qwen_call_cut_off_before_its_wrapper_closes_is_kept() { + let reply = "Paris"; + let expected = ("get_weather".to_string(), json!({"city": "Paris"})); + assert_eq!(cut_off_call(reply).await, [expected.clone(), expected]); + let prose = " and then its parameters"; + let [unary, _] = cut_off_call(prose).await; + assert_eq!(unary, (String::new(), Value::Null)); + } + + /// A qwen_xml call outside a `` wrapper is a call, whole or cut off, as + /// ATOM's HTTP parser reads one; a bare name prose follows is not. + #[tokio::test] + async fn a_bare_qwen_function_call_is_a_call() { + let expected = ("get_weather".to_string(), json!({"city": "Paris"})); + for reply in [ + "Paris", + "Checking.\n\nParis", + ] { + assert_eq!( + cut_off_call(reply).await, + [expected.clone(), expected.clone()] + ); + } + let prose = "Write and then its parameters."; + let none = (String::new(), Value::Null); + assert_eq!(cut_off_call(prose).await, [none.clone(), none]); + // Nor does a name quoted before a call take that call's parameters. + let quoted = "Use here. \ + Paris"; + assert_eq!(cut_off_call(quoted).await, [expected.clone(), expected]); + } + + /// A bare qwen_xml call cut off at its declared name, or inside the tag after it, is + /// kept, as ATOM's HTTP parser keeps it at end of input; a cut-off name is not. + #[tokio::test] + async fn a_bare_qwen_call_cut_off_after_its_name_is_kept() { + let expected = ("get_weather".to_string(), json!({})); + for reply in ["", "", + " so", + ] { + assert_eq!(cut_off_call(reply).await, [none.clone(), none.clone()]); + } + } + + /// A bare qwen_xml call cut off in a parameter's name, or in a tag after a closed + /// parameter, is kept, as ATOM's HTTP parser keeps it at end of input. + #[tokio::test] + async fn a_bare_qwen_call_cut_off_in_a_tag_is_kept() { + let empty = ("get_weather".to_string(), json!({})); + let read = cut_off_call(" [(String, String); 2] { + let ids = tokenizer() + .encode(reply, false) + .unwrap() + .token_ids() + .to_vec(); + let mut read = Vec::new(); + for stream in [false, true] { + let mut ctx = ctx(stream, json!("auto")); + ctx.configured_tool_parser = Some("qwen_xml".to_string()); + ctx.reads_as_atom = reads_as_atom; + let complete = TokenChunk::Complete { + token_ids: ids.clone(), + finish_reason: FinishReason::Stop, + matched_stop: None, + usage: Usage::default(), + logprobs: None, + input_logprobs: None, + meta: WorkerMeta::default(), + }; + let stream_of = synthetic_single_stream(vec![Ok(complete)]); + let (mut content, mut names) = (String::new(), String::new()); + let messages: Vec = if stream { + let resp = chat_streaming::process(stream_of, ctx, "regular"); + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let body = String::from_utf8_lossy(&body).into_owned(); + (body.lines()) + .filter_map(|line| line.strip_prefix("data: ")) + .filter_map(|data| serde_json::from_str::(data).ok()) + .map(|event| event["choices"][0]["delta"].clone()) + .collect() + } else { + let resp = chat_aggregator::process(stream_of, ctx).await; + let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + let json: Value = serde_json::from_slice(&body).unwrap(); + vec![json["choices"][0]["message"].clone()] + }; + for message in messages { + content.push_str(message["content"].as_str().unwrap_or_default()); + for call in message["tool_calls"].as_array().into_iter().flatten() { + names.push_str(call["function"]["name"].as_str().unwrap_or_default()); + } + } + read.push((content, names)); + } + read.try_into().unwrap() + } + + /// A bare qwen_xml call is a call in an ATOM worker's reply only: SGLang's and vLLM's + /// HTTP chats return it as text. + #[tokio::test] + async fn only_an_atom_reply_reads_a_bare_qwen_function_call_as_a_call() { + let reply = "Sure. Paris"; + let call = ("Sure. ".to_string(), "get_weather".to_string()); + assert_eq!(read_qwen_xml(reply, true).await, [call.clone(), call]); + let text = (reply.to_string(), String::new()); + assert_eq!(read_qwen_xml(reply, false).await, [text.clone(), text]); + } + + /// An ATOM reply's text streams as it reads unary: prose quoting `` + /// before a bare call, and a last tag no call followed, stay text. + #[tokio::test] + async fn an_atom_reply_s_text_streams_as_it_reads_unary() { + let reply = "Use as the wrapper. \ + Paris"; + let prose = "Use as the wrapper. ".to_string(); + let call = (prose, "get_weather".to_string()); + assert_eq!(read_qwen_xml(reply, true).await, [call.clone(), call]); + for reply in ["The prefix is Paris After"; + let call = ("Before After".to_string(), "get_weather".to_string()); + assert_eq!(read_qwen_xml(reply, true).await, [call.clone(), call]); + } + + /// A MiniMax-M3 call cut off inside a parameter keeps its value, as ATOM's HTTP + /// parser does at end of input. + #[tokio::test] + async fn a_minimax_call_cut_off_inside_a_parameter_keeps_its_value() { + let ns = crate::tool_parser::parsers::minimax::MINIMAX_NS; + let reply = format!("{ns}{ns}{ns}Paris"); + let expected = ("get_weather".to_string(), json!({"city": "Paris"})); + let read = cut_off_call_with(&reply, "minimax", None).await; + assert_eq!(read, [expected.clone(), expected]); + } +} + /// A streamed response dropped while its source waits for output drops the source, /// which ends its call and frees the loads it holds. mod c3_streaming_client_disconnect { diff --git a/atom/mesh/src/routers/test_mocks/app_context.rs b/atom/mesh/src/routers/test_mocks/app_context.rs index 99e930c6a06..553f5909b9c 100644 --- a/atom/mesh/src/routers/test_mocks/app_context.rs +++ b/atom/mesh/src/routers/test_mocks/app_context.rs @@ -65,3 +65,11 @@ fn app_context_configured( .expect("test AppContext must build"); Arc::new(ctx) } + +/// Records that `model`'s tokenizer was loaded with an ATOM worker's `template`, as +/// registration does, so its chats pass the readiness check. +pub(crate) fn loaded_with_worker_template(ctx: &AppContext, model: &str, template: &str) { + let id = ctx.tokenizer_registry.get_by_name(model).unwrap().id; + let templates = &ctx.tokenizer_inline_templates; + templates.write().insert(id, template.to_string()); +} diff --git a/atom/mesh/src/tool_parser/core.rs b/atom/mesh/src/tool_parser/core.rs index a22ede8dee9..43c32aac54d 100644 --- a/atom/mesh/src/tool_parser/core.rs +++ b/atom/mesh/src/tool_parser/core.rs @@ -135,6 +135,23 @@ pub trait ToolParser: Send + Sync { None } + /// After `parse_incremental` has read a whole reply, the markup that closes the + /// call the reply was cut off in, as ATOM's HTTP parser for the format keeps such a + /// call at end of input; `None` when no call is open, or the open one reads as prose. + fn end_of_input_closers(&self, _tools: &[Tool]) -> Option { + None + } + + /// After `end_of_input_closers` is read: the text the parser still holds as the + /// possible start of a call that never came, which is the reply's text. + fn end_of_input_text(&mut self) -> String { + String::new() + } + + /// Read replies as ATOM's HTTP parser for the format does, where that differs from + /// SGLang's and vLLM's; set on a parser made for an ATOM worker's reply. + fn read_as_atom(&mut self) {} + /// Reset the parser state for reuse across requests. /// This should clear all buffers and reset state to initial values. fn reset(&mut self) { diff --git a/atom/mesh/src/tool_parser/parsers/minimax.rs b/atom/mesh/src/tool_parser/parsers/minimax.rs index ab7b179c977..1ade6c0193e 100644 --- a/atom/mesh/src/tool_parser/parsers/minimax.rs +++ b/atom/mesh/src/tool_parser/parsers/minimax.rs @@ -29,6 +29,8 @@ pub struct MiniMaxParser { invoke_complete: Regex, invoke_name_attr: Regex, parameter: Regex, + /// A parameter's opening tag. + parameter_open: Regex, buffer: String, prev_tool_call_arr: Vec, current_tool_id: i32, @@ -57,6 +59,7 @@ impl MiniMaxParser { // both tag names and verify their equality while parsing. parameter: Regex::new(r"(?s)<([\w-]+)>(.*?)") .expect("valid MiniMax parameter pattern"), + parameter_open: Regex::new(r"<([\w-]+)>").expect("valid MiniMax opening tag pattern"), buffer: String::new(), prev_tool_call_arr: Vec::new(), current_tool_id: -1, @@ -459,6 +462,49 @@ impl ToolParser for MiniMaxParser { text.contains(MINIMAX_NS) } + /// As `minimax_tool_parser._is_truncated_call` reads an open `` at + /// end of input: a call when nothing, or a parameter tag (a declared one, when the + /// tool declares any), whole or cut off, follows it; then its open tags are closed. + fn end_of_input_closers(&self, tools: &[Tool]) -> Option { + if !(self.in_tool_call && self.function_name_sent) { + return None; + } + let rest = self.buffer.trim_start(); + let types = helpers::param_types_for_function(tools, &self.current_function_name); + let followers: Vec = match types.is_empty() { + true => vec!["<".to_string()], + false => types.keys().map(|tag| format!("<{tag}>")).collect(), + }; + let continues = + |token: &String| rest.starts_with(token.as_str()) || token.starts_with(rest); + if !rest.is_empty() && !followers.iter().any(continues) { + return None; + } + let mut closers = String::new(); + let last_open = self + .parameter_open + .captures_iter(rest) + .filter(|tag| tag.get(1).is_some_and(|name| name.as_str() != "invoke")) + .last(); + if let Some(open) = last_open { + let (whole, tag) = (open.get(0).unwrap(), &open[1]); + if !rest[whole.end()..].contains(&format!("")) { + closers.push_str(&format!("")); + } + } + closers.push_str(self.invoke_end_token); + closers.push_str(self.tool_call_end_token); + Some(closers) + } + + /// Outside a call, the partial marker the parser holds is text. + fn end_of_input_text(&mut self) -> String { + match self.in_tool_call { + true => String::new(), + false => std::mem::take(&mut self.buffer), + } + } + fn get_unstreamed_tool_args(&self) -> Option> { helpers::get_unstreamed_args(&self.prev_tool_call_arr, &self.streamed_args_for_tool) } @@ -697,6 +743,25 @@ mod tests { assert!(calls[1].function.arguments.contains("London")); } + /// Text held at end of input as a possible marker, outside a call, is text. + #[tokio::test] + async fn a_held_partial_marker_is_text_at_end_of_input() { + for reply in ["The prefix is ` calls are calls (`read_as_atom`). + bare_calls: bool, + /// The open call is a bare ``, outside a `` wrapper. + bare_call: bool, current_function_name: String, current_parameters: serde_json::Map, @@ -57,6 +63,20 @@ mod coder { xml_param_pattern: Regex, } + /// A call ATOM's HTTP parser reads outside a `` wrapper too. + const BARE_CALL_START: &str = " = LazyLock::new(|| { + let pattern = concat!( + r"(?s)\s*(.*?)\s*", + r"|(]*>(?:\s*]*>.*?)*", + r"(?:\s*]*)?\s*)", + ); + Regex::new(pattern).expect("Valid regex pattern") + }); + /// Decode HTML entities in a string (equivalent to Python's html.unescape) /// /// Handles common HTML entities like & < > " ' and numeric entities @@ -181,6 +201,8 @@ mod coder { tool_call_start_token: "", tool_call_end_token: "", in_tool_call: false, + bare_calls: false, + bare_call: false, current_function_name: String::new(), current_parameters: serde_json::Map::new(), xml_function_pattern, @@ -241,9 +263,11 @@ mod coder { let mut calls: Vec = vec![]; let param_types = helpers::param_types_for_function(tools, &self.current_function_name); - // Find all complete parameter patterns in buffer + // Find all complete parameter patterns in the open call, not in calls after it let mut new_params = serde_json::Map::new(); - for cap in self.xml_param_pattern.captures_iter(&self.buffer) { + let end = self.buffer.find(self.call_end_token()); + let call = &self.buffer[..end.unwrap_or(self.buffer.len())]; + for cap in self.xml_param_pattern.captures_iter(call) { if let (Some(key_match), Some(value_match)) = (cap.get(1), cap.get(2)) { let key = key_match.as_str().trim().to_string(); let value = value_match.as_str(); @@ -323,31 +347,67 @@ mod coder { return Ok((text.to_string(), vec![])); } - let Some(idx) = text.find(self.tool_call_start_token) else { - return Ok((text.to_string(), vec![])); - }; - let normal_text = text[..idx].to_string(); - let mut parsed = Vec::new(); + let tool_indices = helpers::get_tool_indices(tools); + let (mut outside, mut end, mut parsed) = (String::new(), 0, Vec::new()); for captures in self.extractor.captures_iter(text) { - if let Some(content) = captures.get(1) { - match self.parse_xml_format(content.as_str().trim(), tools) { - Ok(Some(tool)) => parsed.push(tool), - Ok(None) => {} - Err(error) => { - tracing::warn!("Failed to parse XML tool call: {:?}", error); - } + let Some(content) = captures.get(1).or_else(|| captures.get(2)) else { + continue; + }; + match self.parse_xml_format(content.as_str().trim(), tools) { + // A bare call names a declared tool, as when streamed; else it is text. + Ok(Some(tool)) + if captures.get(1).is_some() + || tool_indices.contains_key(&tool.function.name) => + { + let call = captures.get(0).unwrap(); + outside.push_str(&text[end..call.start()]); + end = call.end(); + parsed.push(tool); + } + Ok(_) => {} + Err(error) => { + tracing::warn!("Failed to parse XML tool call: {:?}", error); } } } if parsed.is_empty() { return Ok((text.to_string(), vec![])); } + let normal_text = match self.bare_calls { + // As ATOM reads it, a reply's text is all of it outside its calls (a + // wrapped one's from its wrapper); a ` outside + &text[end..], + false => text[..text.find(self.tool_call_start_token).unwrap_or(0)].to_string(), + }; Ok((normal_text, parsed)) } + /// Where the first call in `text` starts, and whether it is a bare ``. + fn call_start(&self, text: &str) -> Option<(usize, bool)> { + let wrapped = text.find(self.tool_call_start_token); + let bare = self + .bare_calls + .then(|| text.find(BARE_CALL_START)) + .flatten(); + match (wrapped, bare) { + (Some(w), Some(b)) if b < w => Some((b, true)), + (Some(w), _) => Some((w, false)), + (None, bare) => bare.map(|b| (b, true)), + } + } + + /// The tag that ends the open call: a bare call's ``, else its wrapper's. + fn call_end_token(&self) -> &'static str { + match self.bare_call { + true => "", + false => self.tool_call_end_token, + } + } + /// Reset streaming state for next tool call fn reset_streaming_state(&mut self) { self.in_tool_call = false; + self.bare_call = false; self.current_tool_name_sent = false; self.current_function_name.clear(); self.current_parameters.clear(); @@ -389,10 +449,11 @@ mod coder { loop { // If we're not in a tool call and don't see a start token, return normal text - if !self.in_tool_call && !self.buffer.contains(self.tool_call_start_token) { + if !self.in_tool_call && self.call_start(&self.buffer).is_none() { // Check for partial start token - if helpers::ends_with_partial_token(&self.buffer, self.tool_call_start_token) - .is_none() + let partial = |token| helpers::ends_with_partial_token(&self.buffer, token); + if partial(self.tool_call_start_token).is_none() + && !(self.bare_calls && partial(BARE_CALL_START).is_some()) { normal_text.push_str(&self.buffer); self.buffer.clear(); @@ -402,11 +463,31 @@ mod coder { // Look for tool call start if !self.in_tool_call { - if let Some(s) = self.buffer.find(self.tool_call_start_token) { + if let Some((s, bare)) = self.call_start(&self.buffer) { + // A bare call keeps its `` no ` s, + false => s + opener, + }; + normal_text.push_str(&self.buffer[..quoted]); + self.buffer.drain(..quoted); + if quoted == s { + break; + } + continue; + } normal_text.push_str(&self.buffer[..s]); - self.buffer = - self.buffer[s + self.tool_call_start_token.len()..].to_string(); + self.buffer = self.buffer[s + opener..].to_string(); self.in_tool_call = true; + self.bare_call = bare; self.current_tool_name_sent = false; self.current_function_name.clear(); self.current_parameters.clear(); @@ -418,7 +499,38 @@ mod coder { // We're in a tool call, try to parse function name if not sent yet if !self.current_tool_name_sent { + // As unary reads it, a bare header's name holds no `<`: up to one, it is prose. + if self.bare_call { + let name = &self.buffer[BARE_CALL_START.len()..]; + let ends = name.find(['<', '>']); + if let Some(cut) = ends.filter(|&at| name[at..].starts_with('<')) { + let cut = BARE_CALL_START.len() + cut; + normal_text.push_str(&self.buffer[..cut]); + self.buffer.drain(..cut); + self.reset_streaming_state(); + continue; + } + } if let Some(captures) = self.xml_function_pattern.captures(&self.buffer) { + let declared = captures.get(0).unwrap().end(); + // A bare one is a call only when it names a tool and call syntax + // follows; else it is prose, and so is its ``. + if self.bare_call { + let named = (captures.get(1)).is_some_and(|name| { + tool_indices.contains_key(name.as_str().trim()) + }); + let rest = self.buffer[declared..].trim_start(); + let call = [""]; + if !(named && call.iter().any(|token| rest.starts_with(token))) { + if named && call.iter().any(|token| token.starts_with(rest)) { + break; + } + normal_text.push_str(&self.buffer[..declared]); + self.buffer.drain(..declared); + self.reset_streaming_state(); + continue; + } + } if let Some(name_match) = captures.get(1) { let function_name = name_match.as_str().trim().to_string(); @@ -477,11 +589,21 @@ mod coder { calls.extend(param_calls); // Check if tool call is complete - if let Some(end_pos) = self.buffer.find(self.tool_call_end_token) { + let end_token = self.call_end_token(); + if let Some(end_pos) = self.buffer.find(end_token) { // Close JSON object if we have parameters let current_args = &self.streamed_args_for_tool[self.current_tool_id as usize]; - if !current_args.is_empty() { + // A call with no parameters has `{}` for arguments. + if current_args.is_empty() { + calls.push(ToolCallItem { + tool_index: self.current_tool_id as usize, + name: None, + parameters: "{}".to_string(), + }); + self.streamed_args_for_tool[self.current_tool_id as usize] + .push_str("{}"); + } else { // Count braces to check if JSON is complete let open_braces = current_args.matches('{').count(); let close_braces = current_args.matches('}').count(); @@ -497,8 +619,7 @@ mod coder { } // Complete the tool call - self.buffer = - self.buffer[end_pos + self.tool_call_end_token.len()..].to_string(); + self.buffer = self.buffer[end_pos + end_token.len()..].to_string(); self.reset_streaming_state(); self.current_tool_id += 1; continue; @@ -515,13 +636,90 @@ mod coder { } fn has_tool_markers(&self, text: &str) -> bool { - text.contains(self.tool_call_start_token) + self.call_start(text).is_some() } fn get_unstreamed_tool_args(&self) -> Option> { helpers::get_unstreamed_args(&self.prev_tool_call_arr, &self.streamed_args_for_tool) } + /// As `QwenXmlParser._is_truncated_call` reads an open `` at end + /// of input: a call when what follows the declared name is a parameter or the + /// function's close, whole or cut off; then its open tags are closed. + fn end_of_input_closers(&self, tools: &[Tool]) -> Option { + if !self.in_tool_call { + return None; + } + let rest = match self.current_tool_name_sent { + true => self.buffer.trim_start(), + // A bare call is held at its declared name until what follows the name arrives. + false => { + let declared = self.xml_function_pattern.captures(&self.buffer)?; + let tool_indices = helpers::get_tool_indices(tools); + if !(self.bare_call && tool_indices.contains_key(declared[1].trim())) { + return None; + } + self.buffer[declared.get(0)?.end()..].trim_start() + } + }; + let followers = [""]; + let continues = |token: &str| rest.starts_with(token) || token.starts_with(rest); + if !followers.into_iter().any(continues) { + return None; + } + // Text after the call's `` is not closed into its wrapper. + let after = rest + .split_once("") + .map(|(_, after)| after.trim()); + if after.is_some_and(|after| !after.is_empty()) { + return None; + } + let mut closers = String::new(); + // Outside a value, a tag cut off is completed, so a bare call rereads whole. + if rest.rfind("") { + let cut = |tag: &'static str| { + helpers::ends_with_partial_token(rest, tag).map(|arrived| &tag[arrived..]) + }; + let tags = ["", ""]; + closers.extend(tags.into_iter().find_map(cut)); + } + let rest = format!("{rest}{closers}"); + // A value is closed; a parameter's cut-off name is no parameter, as on HTTP. + if let Some(open) = rest.rfind(" rest.rfind("") && rest[open..].contains('>') { + closers.push_str(""); + } + } + if !rest.contains("") { + closers.push_str(""); + } + if !self.bare_call { + closers.push_str(self.tool_call_end_token); + } + Some(closers) + } + + fn end_of_input_text(&mut self) -> String { + if self.in_tool_call && self.current_tool_name_sent { + return String::new(); + } + let opener = match self.in_tool_call && !self.bare_call { + true => self.tool_call_start_token, + false => "", + }; + let text = format!("{opener}{}", self.buffer); + self.buffer.clear(); + self.reset_streaming_state(); + text + } + + /// ATOM's HTTP parser reads a bare `` call as a call; SGLang's and + /// vLLM's return it as text. + fn read_as_atom(&mut self) { + self.bare_calls = true; + self.extractor = WRAPPED_OR_BARE_CALLS.clone(); + } + fn reset(&mut self) { helpers::reset_parser_state( &mut self.buffer, @@ -538,6 +736,279 @@ mod coder { mod tests { use super::*; + /// Closing a call cut off at the end of a long reply reads only the open call the + /// parser still holds: the prose before it is released, not kept. + #[tokio::test] + async fn end_of_input_closers_read_only_the_open_call() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let tools = [tool]; + let mut parser = QwenCoderParser::new(); + let prose = "word ".repeat(200_000); + parser.parse_incremental(&prose, &tools).await.unwrap(); + let call = "Paris"; + parser.parse_incremental(call, &tools).await.unwrap(); + assert!( + parser.buffer.len() < 64, + "{} bytes held", + parser.buffer.len() + ); + let closers = parser.end_of_input_closers(&tools); + assert_eq!( + closers.as_deref(), + Some("") + ); + } + + /// A bare `` call streams as one, the text before it as text; a + /// bare name that prose follows stays text. + #[tokio::test] + async fn a_bare_function_call_streams_as_a_call() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let tools = [tool]; + let reply = "Sure. Paris"; + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let (mut text, mut name, mut args) = (String::new(), String::new(), String::new()); + for piece in reply.as_bytes().chunks(5) { + let piece = std::str::from_utf8(piece).unwrap(); + let result = parser.parse_incremental(piece, &tools).await.unwrap(); + text.push_str(&result.normal_text); + for call in result.calls { + name.push_str(call.name.as_deref().unwrap_or_default()); + args.push_str(&call.parameters); + } + } + assert_eq!((text.as_str(), name.as_str()), ("Sure. ", "get_weather")); + assert_eq!(args, r#"{"city": "Paris"}"#); + + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let prose = "Write then its parameters."; + let result = parser.parse_incremental(prose, &tools).await.unwrap(); + assert_eq!(result.normal_text, prose); + assert!(result.calls.is_empty()); + } + + /// A parser not reading as ATOM returns a bare call as text, unary and streamed, + /// as SGLang's and vLLM's do. + #[tokio::test] + async fn a_bare_function_call_is_text_unless_read_as_atom() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let tools = [tool]; + let reply = "Sure. Paris"; + let mut parser = QwenCoderParser::new(); + let (text, calls) = parser + .parse_complete_with_tools(reply, &tools) + .await + .unwrap(); + assert_eq!((text.as_str(), calls.len()), (reply, 0)); + let mut streamed = String::new(); + for piece in reply.as_bytes().chunks(5) { + let piece = std::str::from_utf8(piece).unwrap(); + let result = parser.parse_incremental(piece, &tools).await.unwrap(); + assert!(result.calls.is_empty()); + streamed.push_str(&result.normal_text); + } + assert_eq!(streamed, reply); + assert!(!parser.has_tool_markers(reply)); + } + + /// A bare call's reply keeps its prose up to the call, a `` it quotes too. + #[tokio::test] + async fn a_quoted_wrapper_before_a_bare_call_stays_text() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let prose = "Use as the wrapper. "; + let reply = format!( + "{prose}Paris" + ); + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let (text, calls) = parser + .parse_complete_with_tools(&reply, &[tool]) + .await + .unwrap(); + assert_eq!((text.as_str(), calls.len()), (prose, 1)); + for size in 1..=9 { + let (streamed, calls) = stream(&reply, size).await; + assert_eq!((streamed.as_str(), calls), (prose, 1), "{size}-byte pieces"); + } + } + + /// What `reply` streams in `size`-byte pieces, then at end of input, read as ATOM + /// with get_weather declared: (text, calls named). + async fn stream(reply: &str, size: usize) -> (String, usize) { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let tools = [tool]; + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let mut read = Vec::new(); + for piece in reply.as_bytes().chunks(size) { + let piece = std::str::from_utf8(piece).unwrap(); + read.push(parser.parse_incremental(piece, &tools).await.unwrap()); + } + if let Some(closers) = parser.end_of_input_closers(&tools) { + read.push(parser.parse_incremental(&closers, &tools).await.unwrap()); + } + let calls = read.iter().flat_map(|result| &result.calls); + let calls = calls.filter(|call| call.name.is_some()).count(); + let mut text: String = read.iter().map(|result| &*result.normal_text).collect(); + text.push_str(&parser.end_of_input_text()); + (text, calls) + } + + /// A bare call naming no declared tool is text, unary as streamed. + #[tokio::test] + async fn a_bare_call_naming_no_declared_tool_is_text() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let reply = "The format is ."; + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let unary = parser.parse_complete_with_tools(reply, &[tool]).await; + let (text, calls) = unary.unwrap(); + assert_eq!((text.as_str(), calls.len()), (reply, 0)); + for size in 1..=9 { + assert_eq!(stream(reply, size).await, (reply.to_string(), 0)); + } + } + + /// A bare header whose name runs into a `<` is text, and a call after it is read, + /// unary as streamed. + #[tokio::test] + async fn a_call_after_an_unclosed_bare_header_is_read() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let prose = "Example "); + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let unary = parser.parse_complete_with_tools(&reply, &[tool]).await; + let (text, calls) = unary.unwrap(); + assert_eq!((text.as_str(), calls.len()), (prose, 1)); + for size in 1..=9 { + let (streamed, calls) = stream(&reply, size).await; + assert_eq!((streamed.as_str(), calls), (prose, 1), "{size}-byte pieces"); + } + } + + /// A reply's text is all of it outside its calls, unary as streamed. + #[tokio::test] + async fn text_between_and_after_calls_is_text() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let call = "Paris"; + let reply = format!("Before {call} Between {call} After"); + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let unary = parser.parse_complete_with_tools(&reply, &[tool]).await; + let (text, calls) = unary.unwrap(); + let outside = "Before Between After"; + assert_eq!((text.as_str(), calls.len()), (outside, 2)); + for size in 1..=9 { + assert_eq!(stream(&reply, size).await, (outside.to_string(), 2)); + } + } + + /// Text a parser holds at end of input as a call's possible start, and that never + /// became one, is text. + #[tokio::test] + async fn a_held_opener_no_call_followed_is_text_at_end_of_input() { + for reply in [ + "The prefix is \n", + ] { + for size in 1..=5 { + let read = stream(reply, size).await; + assert_eq!(read, (reply.to_string(), 0), "{size}-byte pieces"); + } + } + } + + /// Each call in one delta streams its own arguments, `{}` when it has none. + #[tokio::test] + async fn calls_in_one_delta_stream_their_own_arguments() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let tools = [tool]; + let call = |city: &str| match city { + "" => "".to_string(), + _ => format!("{city}"), + }; + for (a, b, args) in [ + ( + "Paris", + "London", + [r#"{"city": "Paris"}"#, r#"{"city": "London"}"#], + ), + ("", "", ["{}", "{}"]), + ] { + let bare = call(a) + &call(b); + let wrapped = format!( + "{}{}", + call(a), + call(b) + ); + for reply in [bare, wrapped] { + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let result = parser.parse_incremental(&reply, &tools).await.unwrap(); + let mut streamed = [String::new(), String::new()]; + for call in result.calls { + streamed[call.tool_index].push_str(&call.parameters); + } + assert_eq!(streamed, args, "{reply}"); + } + } + } + + /// A cut-off wrapper is not closed past text that follows the call's ``. + #[tokio::test] + async fn text_after_a_cut_off_wrapper_s_function_is_not_closed_into_the_call() { + let tool: Tool = serde_json::from_value(serde_json::json!({ + "type": "function", "function": {"name": "get_weather", "parameters": {}}, + })) + .unwrap(); + let tools = [tool]; + let reply = "Before Paris After"; + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + parser.parse_incremental(reply, &tools).await.unwrap(); + assert_eq!(parser.end_of_input_closers(&tools), None); + let mut parser = QwenCoderParser::new(); + parser.read_as_atom(); + let (text, calls) = parser + .parse_complete_with_tools(reply, &tools) + .await + .unwrap(); + assert!(text.ends_with(" After") && calls.len() == 1, "{text}"); + } + #[test] fn test_html_unescape_basic() { assert_eq!(html_unescape("&"), "&"); diff --git a/atom/mesh/src/tool_parser/registry.rs b/atom/mesh/src/tool_parser/registry.rs index 0d199dbfcad..cb9184610cf 100644 --- a/atom/mesh/src/tool_parser/registry.rs +++ b/atom/mesh/src/tool_parser/registry.rs @@ -376,6 +376,21 @@ pub(crate) fn create_tool_parser( } } +/// `create_tool_parser`, reading the reply as ATOM's HTTP parser for its format does when +/// an ATOM worker wrote it (`ToolParser::read_as_atom`). +pub(crate) fn create_reply_tool_parser( + factory: &ParserFactory, + configured_parser: Option<&str>, + model: &str, + reads_as_atom: bool, +) -> Option> { + let mut parser = create_tool_parser(factory, configured_parser, model)?; + if reads_as_atom { + parser.read_as_atom(); + } + Some(parser) +} + #[cfg(test)] mod tests { use super::ParserFactory; diff --git a/atom/mesh/tests/fixtures/sse_golden/chat_sglang_pd.bin b/atom/mesh/tests/fixtures/sse_golden/chat_sglang_pd.bin index 6cd0300a1f3..39bdc38ea3f 100644 --- a/atom/mesh/tests/fixtures/sse_golden/chat_sglang_pd.bin +++ b/atom/mesh/tests/fixtures/sse_golden/chat_sglang_pd.bin @@ -4,6 +4,8 @@ data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000, data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"role":"assistant","content":" world","reasoning_content":null},"logprobs":null,"finish_reason":null}]} +data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"role":"assistant","content":" .","reasoning_content":null},"logprobs":null,"finish_reason":null}]} + data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"reasoning_content":null},"logprobs":null,"finish_reason":"stop"}]} data: [DONE] diff --git a/atom/mesh/tests/fixtures/sse_golden/chat_sglang_regular.bin b/atom/mesh/tests/fixtures/sse_golden/chat_sglang_regular.bin index 6cd0300a1f3..39bdc38ea3f 100644 --- a/atom/mesh/tests/fixtures/sse_golden/chat_sglang_regular.bin +++ b/atom/mesh/tests/fixtures/sse_golden/chat_sglang_regular.bin @@ -4,6 +4,8 @@ data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000, data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"role":"assistant","content":" world","reasoning_content":null},"logprobs":null,"finish_reason":null}]} +data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"role":"assistant","content":" .","reasoning_content":null},"logprobs":null,"finish_reason":null}]} + data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"reasoning_content":null},"logprobs":null,"finish_reason":"stop"}]} data: [DONE] diff --git a/atom/mesh/tests/fixtures/sse_golden/chat_vllm_pd.bin b/atom/mesh/tests/fixtures/sse_golden/chat_vllm_pd.bin index 6cd0300a1f3..39bdc38ea3f 100644 --- a/atom/mesh/tests/fixtures/sse_golden/chat_vllm_pd.bin +++ b/atom/mesh/tests/fixtures/sse_golden/chat_vllm_pd.bin @@ -4,6 +4,8 @@ data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000, data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"role":"assistant","content":" world","reasoning_content":null},"logprobs":null,"finish_reason":null}]} +data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"role":"assistant","content":" .","reasoning_content":null},"logprobs":null,"finish_reason":null}]} + data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"reasoning_content":null},"logprobs":null,"finish_reason":"stop"}]} data: [DONE] diff --git a/atom/mesh/tests/fixtures/sse_golden/chat_vllm_regular.bin b/atom/mesh/tests/fixtures/sse_golden/chat_vllm_regular.bin index 6cd0300a1f3..39bdc38ea3f 100644 --- a/atom/mesh/tests/fixtures/sse_golden/chat_vllm_regular.bin +++ b/atom/mesh/tests/fixtures/sse_golden/chat_vllm_regular.bin @@ -4,6 +4,8 @@ data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000, data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"role":"assistant","content":" world","reasoning_content":null},"logprobs":null,"finish_reason":null}]} +data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"role":"assistant","content":" .","reasoning_content":null},"logprobs":null,"finish_reason":null}]} + data: {"id":"req-fixture","object":"chat.completion.chunk","created":1700000000,"model":"mock-model","choices":[{"index":0,"delta":{"reasoning_content":null},"logprobs":null,"finish_reason":"stop"}]} data: [DONE] diff --git a/atom/mesh/tests/fixtures/sse_golden/generate_sglang_pd.bin b/atom/mesh/tests/fixtures/sse_golden/generate_sglang_pd.bin index a15f6dc4d5b..7265722af9a 100644 --- a/atom/mesh/tests/fixtures/sse_golden/generate_sglang_pd.bin +++ b/atom/mesh/tests/fixtures/sse_golden/generate_sglang_pd.bin @@ -2,7 +2,7 @@ data: {"text":"Hello","output_ids":[1],"meta_info":{"id":"req-fixture-0","finish data: {"text":"Hello world","output_ids":[2],"meta_info":{"id":"req-fixture-0","finish_reason":null,"prompt_tokens":0,"weight_version":"default","output_token_logprobs":null,"completion_tokens":2,"cached_tokens":0},"index":0} -data: {"text":"Hello world","output_ids":[6],"meta_info":{"id":"req-fixture-0","finish_reason":{"type":"stop"},"prompt_tokens":3,"weight_version":"default","input_token_logprobs":null,"output_token_logprobs":null,"completion_tokens":3,"cached_tokens":0,"e2e_latency":0.0},"index":0} +data: {"text":"Hello world .","output_ids":[6],"meta_info":{"id":"req-fixture-0","finish_reason":{"type":"stop"},"prompt_tokens":3,"weight_version":"default","input_token_logprobs":null,"output_token_logprobs":null,"completion_tokens":3,"cached_tokens":0,"e2e_latency":0.0},"index":0} data: [DONE] diff --git a/atom/mesh/tests/fixtures/sse_golden/generate_sglang_regular.bin b/atom/mesh/tests/fixtures/sse_golden/generate_sglang_regular.bin index a15f6dc4d5b..7265722af9a 100644 --- a/atom/mesh/tests/fixtures/sse_golden/generate_sglang_regular.bin +++ b/atom/mesh/tests/fixtures/sse_golden/generate_sglang_regular.bin @@ -2,7 +2,7 @@ data: {"text":"Hello","output_ids":[1],"meta_info":{"id":"req-fixture-0","finish data: {"text":"Hello world","output_ids":[2],"meta_info":{"id":"req-fixture-0","finish_reason":null,"prompt_tokens":0,"weight_version":"default","output_token_logprobs":null,"completion_tokens":2,"cached_tokens":0},"index":0} -data: {"text":"Hello world","output_ids":[6],"meta_info":{"id":"req-fixture-0","finish_reason":{"type":"stop"},"prompt_tokens":3,"weight_version":"default","input_token_logprobs":null,"output_token_logprobs":null,"completion_tokens":3,"cached_tokens":0,"e2e_latency":0.0},"index":0} +data: {"text":"Hello world .","output_ids":[6],"meta_info":{"id":"req-fixture-0","finish_reason":{"type":"stop"},"prompt_tokens":3,"weight_version":"default","input_token_logprobs":null,"output_token_logprobs":null,"completion_tokens":3,"cached_tokens":0,"e2e_latency":0.0},"index":0} data: [DONE] diff --git a/atom/mesh/tests/fixtures/sse_golden/generate_vllm_pd.bin b/atom/mesh/tests/fixtures/sse_golden/generate_vllm_pd.bin index a15f6dc4d5b..7265722af9a 100644 --- a/atom/mesh/tests/fixtures/sse_golden/generate_vllm_pd.bin +++ b/atom/mesh/tests/fixtures/sse_golden/generate_vllm_pd.bin @@ -2,7 +2,7 @@ data: {"text":"Hello","output_ids":[1],"meta_info":{"id":"req-fixture-0","finish data: {"text":"Hello world","output_ids":[2],"meta_info":{"id":"req-fixture-0","finish_reason":null,"prompt_tokens":0,"weight_version":"default","output_token_logprobs":null,"completion_tokens":2,"cached_tokens":0},"index":0} -data: {"text":"Hello world","output_ids":[6],"meta_info":{"id":"req-fixture-0","finish_reason":{"type":"stop"},"prompt_tokens":3,"weight_version":"default","input_token_logprobs":null,"output_token_logprobs":null,"completion_tokens":3,"cached_tokens":0,"e2e_latency":0.0},"index":0} +data: {"text":"Hello world .","output_ids":[6],"meta_info":{"id":"req-fixture-0","finish_reason":{"type":"stop"},"prompt_tokens":3,"weight_version":"default","input_token_logprobs":null,"output_token_logprobs":null,"completion_tokens":3,"cached_tokens":0,"e2e_latency":0.0},"index":0} data: [DONE] diff --git a/atom/mesh/tests/fixtures/sse_golden/generate_vllm_regular.bin b/atom/mesh/tests/fixtures/sse_golden/generate_vllm_regular.bin index a15f6dc4d5b..7265722af9a 100644 --- a/atom/mesh/tests/fixtures/sse_golden/generate_vllm_regular.bin +++ b/atom/mesh/tests/fixtures/sse_golden/generate_vllm_regular.bin @@ -2,7 +2,7 @@ data: {"text":"Hello","output_ids":[1],"meta_info":{"id":"req-fixture-0","finish data: {"text":"Hello world","output_ids":[2],"meta_info":{"id":"req-fixture-0","finish_reason":null,"prompt_tokens":0,"weight_version":"default","output_token_logprobs":null,"completion_tokens":2,"cached_tokens":0},"index":0} -data: {"text":"Hello world","output_ids":[6],"meta_info":{"id":"req-fixture-0","finish_reason":{"type":"stop"},"prompt_tokens":3,"weight_version":"default","input_token_logprobs":null,"output_token_logprobs":null,"completion_tokens":3,"cached_tokens":0,"e2e_latency":0.0},"index":0} +data: {"text":"Hello world .","output_ids":[6],"meta_info":{"id":"req-fixture-0","finish_reason":{"type":"stop"},"prompt_tokens":3,"weight_version":"default","input_token_logprobs":null,"output_token_logprobs":null,"completion_tokens":3,"cached_tokens":0,"e2e_latency":0.0},"index":0} data: [DONE] diff --git a/atom/mesh/tests/grpc_proto_snapshot.rs b/atom/mesh/tests/grpc_proto_snapshot.rs index b9f62804065..c4a7b189e04 100644 --- a/atom/mesh/tests/grpc_proto_snapshot.rs +++ b/atom/mesh/tests/grpc_proto_snapshot.rs @@ -414,6 +414,7 @@ fn scenario_a_payload() -> GenerationPayload { stream: false, return_hidden_states: false, log_metrics: false, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, @@ -504,6 +505,7 @@ fn scenario_b_payload() -> GenerationPayload { // GenerateRequest.log_metrics defaults to true (serde default_true); // our payload mirrors that for parity with upstream's plain builder. log_metrics: true, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, @@ -588,6 +590,7 @@ fn scenario_c_payload() -> GenerationPayload { stream: false, return_hidden_states: false, log_metrics: false, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, @@ -684,6 +687,7 @@ fn scenario_d_payload() -> GenerationPayload { stream: false, return_hidden_states: false, log_metrics: false, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, @@ -808,6 +812,7 @@ fn scenario_b_prime_payload() -> GenerationPayload { stream: false, return_hidden_states: false, log_metrics: true, + structured_output: None, dp_session_id: None, dp_parent_session_id: None, chat_template: None, diff --git a/atom/mesh/tests/grpc_sse_snapshot.rs b/atom/mesh/tests/grpc_sse_snapshot.rs index 8617a61593d..1f58ca55ca3 100644 --- a/atom/mesh/tests/grpc_sse_snapshot.rs +++ b/atom/mesh/tests/grpc_sse_snapshot.rs @@ -62,6 +62,8 @@ fn chat_ctx() -> ResponseContext { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } } @@ -86,6 +88,8 @@ fn generate_ctx() -> ResponseContext { configured_tool_parser: None, configured_reasoning_parser: None, prompt_opener: None, + reads_as_atom: false, + usage_on_finish: false, } }