Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(api): opt-in reasoning_content on chat completions via include_reasoning (#728)
Krisztian Gajdar24400dfda0c6
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 46e861d51..90dd54294 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -209,6 +209,13 @@"content": {"type": "string"},+ "reasoning_content": {+ "description": "The model's reasoning. Present only when the request set\n``include_reasoning: true`` and the model produced any; streaming\nresponses carry it as ``delta.reasoning_content``.",+ "type": [+ "string",+ "null"+ ]+ },"role": {"type": "string"},@@ -380,6 +387,13 @@"null"]},+ "include_reasoning": {+ "description": "SIE extension. `true` makes the model's reasoning public as `reasoning_content` on the message and, when streaming, on each delta. A model whose configuration declares no reasoning answers the field with nothing. Absent or `false` keeps reasoning private; `usage` is unchanged either way.",+ "type": [+ "boolean",+ "null"+ ]+ },"logit_bias": {"additionalProperties": {"format": "double",diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 8d26e18d7..3dee42e15 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -6436,6 +6436,10 @@ struct ChatRequestParams {/// rendered prompt. ``None`` leaves it to the serving profile/// (default on).schema_in_prompt: Option<bool>,+ /// SIE extension ``include_reasoning``: ``true`` asks the worker to+ /// publish the model's reasoning as ``reasoning_content`` on the+ /// message and on stream deltas. Absent or ``false`` keeps it private.+ include_reasoning: Option<bool>,/// OpenAI ``stream`` flag. ``true`` switches the handler to the/// SSE response branch; ``false`` (default) uses the existing/// aggregating path. Parsed by :func:`chat_params_from_json`;@@ -6519,6 +6523,7 @@ impl ChatRequestParams {chat_template_kwargs: self.chat_template_kwargs,grammar: self.grammar,schema_in_prompt: self.schema_in_prompt,+ include_reasoning: self.include_reasoning,routing_key: self.routing_key.clone(),prompt_cache_key: self.prompt_cache_key.clone(),tools: self.tools,@@ -7782,6 +7787,19 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {);}};+ // SIE extension: ``include_reasoning: true`` makes the model's reasoning+ // public as ``reasoning_content``. Absent or ``null`` keeps it private.+ let include_reasoning = match obj.get("include_reasoning") {+ None | Some(serde_json::Value::Null) => None,+ Some(serde_json::Value::Bool(b)) => Some(*b),+ Some(_) => {+ return bad(+ "'include_reasoning' must be a boolean",+ Some("include_reasoning"),+ oai_code::INVALID_REQUEST,+ );+ }+ };// ``tool_choice`` without ``tools`` is meaningless; OpenAI itself// returns a 400 in that case. We mirror the behaviour so SDKs that// accidentally send ``tool_choice: "auto"`` on a plain chat call@@ -7856,6 +7874,7 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {"routing_key","response_format","schema_in_prompt",+ "include_reasoning","stream","tools","tool_choice",@@ -7907,6 +7926,7 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {prompt_cache_key,grammar,schema_in_prompt,+ include_reasoning,stream,stream_include_usage,tools,@@ -8300,6 +8320,7 @@ fn build_chat_completion_body(model: &str,request_id: &str,outcome: &crate::queue::streaming::StreamOutcome,+ include_reasoning: bool,) -> Result<Vec<u8>, Response> {let Some(usage) = outcome.usage.as_ref() else {return Err((@@ -8345,6 +8366,9 @@ fn build_chat_completion_body(} else {message.insert("content".to_string(), json!(outcome.text));}+ if let Some(reasoning) = outcome.reasoning.get(&0).filter(|_| include_reasoning) {+ message.insert("reasoning_content".to_string(), json!(reasoning));+ }vec![json!({"index": 0,"message": Value::Object(message),@@ -8376,6 +8400,14 @@ fn build_chat_completion_body(} else {message.insert("content".to_string(), json!(cand.text));}+ let reasoning = cand+ .reasoning_content+ .as_ref()+ .or_else(|| outcome.reasoning.get(&(i as u32)))+ .filter(|_| include_reasoning);+ if let Some(reasoning) = reasoning {+ message.insert("reasoning_content".to_string(), json!(reasoning));+ }json!({"index": i,"message": Value::Object(message),@@ -9686,6 +9718,7 @@ async fn proxy_chat_inner(let requested_model = params.model.clone();let stream = params.stream;let stream_include_usage = params.stream_include_usage;+ let include_reasoning = params.include_reasoning == Some(true);let mut work_params = params.into_work_params();work_params.require_execution_authority_v1 = require_execution_authority_v1;work_params.fallback_reason = fallback_reason;@@ -9720,6 +9753,7 @@ async fn proxy_chat_inner(work_params,endpoint: super::sse::SseEndpoint::Chat {include_usage: stream_include_usage,+ include_reasoning,},route: RouteKind::Compatibility,})@@ -9755,10 +9789,11 @@ async fn proxy_chat_inner(};let elapsed = start.elapsed();- let body_bytes = match build_chat_completion_body(&model_name, &request_id, &outcome) {- Ok(b) => b,- Err(resp) => return resp,- };+ let body_bytes =+ match build_chat_completion_body(&model_name, &request_id, &outcome, include_reasoning) {+ Ok(b) => b,+ Err(resp) => return resp,+ };state.registry.record_request("queue").await;emit_audit_log(AuditEntry {@@ -14103,6 +14138,7 @@ fn generate_params_from_json(best_of: None,stream,lora_adapter,+ include_reasoning: None,}))}@@ -14532,6 +14568,7 @@ fn generate_params_from_rmpv(best_of: None,stream,lora_adapter,+ include_reasoning: None,}))}@@ -16849,6 +16886,7 @@ mod tests {executed_bundle_config_hash: Some(execution_hash.clone()),execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};insert_buffered_generation_model_revision_header(&mut headers,@@ -16958,6 +16996,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: Some(identity.clone()),execution_binding_sha256: None,+ reasoning: Default::default(),};insert_stream_execution_identity_header(&mut headers, &outcome);assert_eq!(@@ -17093,6 +17132,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: Some(binding.clone()),+ reasoning: Default::default(),};insert_stream_execution_binding_header(&mut headers, &outcome);assert_eq!(@@ -17477,9 +17517,36 @@ mod tests {struct GenerationTargetProbe {targets: std::sync::Mutex<Vec<(String, PublishTarget)>>,params: std::sync::Mutex<Vec<WorkParams>>,+ worker_chunks: std::sync::Mutex<Vec<serde_json::Value>>,}impl GenerationTargetProbe {+ fn collect_worker_chunks(+ &self,+ display_model: &str,+ ) -> Option<(+ oneshot::Receiver<StreamOutcome>,+ broadcast::Receiver<ChunkEnvelope>,+ )> {+ let chunks = self.worker_chunks.lock().expect("chunk probe lock").clone();+ if chunks.is_empty() {+ return None;+ }+ let (tx, rx) = oneshot::channel();+ let mut collector = crate::queue::streaming::StreamCollector::new(+ tx,+ display_model.to_string(),+ "default".to_string(),+ );+ let tap = collector.install_chunk_tap();+ for chunk in chunks {+ collector.apply(serde_json::from_value(chunk).expect("worker chunk"));+ }+ let outcome = collector.build_outcome().expect("worker terminal");+ collector.sender.take().unwrap().send(outcome).unwrap();+ Some((rx, tap))+ }+fn take_params(&self) -> WorkParams {self.params.lock()@@ -17561,6 +17628,14 @@ mod tests {.lock().expect("target probe lock").push((display_model.to_string(), target));+ if let Some((rx, _tap)) = self.collect_worker_chunks(display_model) {+ return Ok((+ "request-1".to_string(),+ rx,+ Arc::new(Notify::new()),+ DispatchDurability::accepted(),+ ));+ }let (tx, rx) = oneshot::channel();tx.send(StreamOutcome {text: "ok".to_string(),@@ -17585,6 +17660,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),}).expect("target probe outcome receiver");Ok((@@ -17620,6 +17696,14 @@ mod tests {.lock().expect("target probe lock").push((display_model.to_string(), target));+ if let Some((rx, tap)) = self.collect_worker_chunks(display_model) {+ return Ok((+ "request-1".to_string(),+ rx,+ tap,+ DispatchDurability::accepted(),+ ));+ }let (tx, rx) = oneshot::channel();let mut collector = crate::queue::streaming::StreamCollector::new(tx,@@ -18313,6 +18397,148 @@ mod tests {}}+ fn reasoning_worker_chunk(seq: u32, fields: serde_json::Value) -> serde_json::Value {+ let mut chunk = json!({+ "kind": "chunk", "request_id": "request-1", "attempt_id": "attempt-1",+ "seq": seq, "text_delta": "", "done": false,+ });+ chunk+ .as_object_mut()+ .unwrap()+ .extend(fields.as_object().unwrap().clone());+ chunk+ }++ fn reasoning_worker_terminal(seq: u32, fields: serde_json::Value) -> serde_json::Value {+ let mut terminal = json!({+ "done": true, "finish_reason": "stop",+ "usage": {"prompt_tokens": 1, "completion_tokens": 3, "total_tokens": 4},+ });+ terminal+ .as_object_mut()+ .unwrap()+ .extend(fields.as_object().unwrap().clone());+ reasoning_worker_chunk(seq, terminal)+ }++ #[tokio::test]+ async fn chat_include_reasoning_reaches_the_worker_and_the_answer_only_when_set() {+ for include_reasoning in [None, Some(false), Some(true)] {+ for stream in [false, true] {+ let (state, probe) = mixed_governed_generation_state(false).await;+ *probe.worker_chunks.lock().unwrap() = vec![+ reasoning_worker_chunk(0, json!({"reasoning_delta": "why "})),+ reasoning_worker_chunk(1, json!({"text_delta": "Hi", "is_first": true})),+ reasoning_worker_terminal(2, json!({})),+ ];+ let mut body = json!({+ "model": "org/g",+ "messages": [{"role": "user", "content": "hello"}],+ "max_tokens": 4,+ "stream": stream,+ });+ if let Some(value) = include_reasoning {+ body["include_reasoning"] = json!(value);+ }+ let response = proxy_chat(+ State(Arc::clone(&state)),+ json_request("/v1/chat/completions", body),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ probe+ .take_params()+ .generate+ .expect("generate")+ .include_reasoning,+ include_reasoning+ );+ let bytes = axum::body::to_bytes(response.into_body(), 1 << 16)+ .await+ .unwrap();+ let expected = (include_reasoning == Some(true)).then_some("why ");+ if stream {+ let text = String::from_utf8(bytes.to_vec()).unwrap();+ let deltas: Vec<serde_json::Value> = text+ .lines()+ .filter_map(|line| line.strip_prefix("data: "))+ .filter(|data| *data != "[DONE]")+ .map(|data| serde_json::from_str::<serde_json::Value>(data).unwrap())+ .filter_map(|event| event["choices"].get(0).map(|c| c["delta"].clone()))+ .collect();+ let reasoning: String = deltas+ .iter()+ .filter_map(|delta| delta["reasoning_content"].as_str())+ .collect();+ let content: String = deltas+ .iter()+ .filter_map(|delta| delta["content"].as_str())+ .collect();+ assert_eq!(content, "Hi");+ assert_eq!(+ (!reasoning.is_empty()).then_some(reasoning.as_str()),+ expected+ );+ } else {+ let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ let message = &value["choices"][0]["message"];+ assert_eq!(message["content"], "Hi");+ assert_eq!(+ message.get("reasoning_content").and_then(|v| v.as_str()),+ expected+ );+ }+ }+ }+ }++ #[tokio::test]+ async fn chat_include_reasoning_keeps_each_candidate_reasoning_on_its_choice() {+ let (state, probe) = mixed_governed_generation_state(false).await;+ *probe.worker_chunks.lock().unwrap() = vec![+ reasoning_worker_chunk(0, json!({"reasoning_delta": "R0"})),+ reasoning_worker_chunk(1, json!({"reasoning_delta": "R1", "choice_index": 1})),+ reasoning_worker_terminal(+ 2,+ json!({"candidates": [+ {"text": "A", "finish_reason": "stop"},+ {"text": "B", "finish_reason": "length"},+ ]}),+ ),+ ];+ let response = proxy_chat(+ State(state),+ json_request(+ "/v1/chat/completions",+ json!({+ "model": "org/g",+ "messages": [{"role": "user", "content": "hello"}],+ "max_tokens": 4,+ "n": 2,+ "include_reasoning": true,+ }),+ ),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), 1 << 16)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ let choices = value["choices"].as_array().expect("choices");+ let answered: Vec<(&str, &str)> = choices+ .iter()+ .map(|choice| {+ (+ choice["message"]["content"].as_str().unwrap(),+ choice["message"]["reasoning_content"].as_str().unwrap(),+ )+ })+ .collect();+ assert_eq!(answered, vec![("A", "R0"), ("B", "R1")]);+ }+#[tokio::test]async fn remote_forbid_numeric_surfaces_publish_a_routed_model_only_to_verified_workers() {for (surface, routed) in [@@ -21949,6 +22175,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};let body = build_generate_success_body_v2("Qwen/Qwen3-4B-Instruct", &outcome, false);let value: serde_json::Value = serde_json::from_slice(&body).unwrap();@@ -25702,6 +25929,46 @@ mod tests {assert_eq!(err["error"]["code"], "invalid_request");}+ // ── include_reasoning: public reasoning on chat completions ──++ #[test]+ fn test_chat_include_reasoning_is_forwarded_and_defaults_to_private() {+ let mut body = _chat_body_min("m");+ let generate = _expect_chat_ok(body.clone())+ .into_work_params()+ .generate+ .expect("generate params");+ assert_eq!(generate.include_reasoning, None);+ let wire = serde_json::to_value(&generate).unwrap();+ assert!(wire.get("include_reasoning").is_none());++ for (value, expected) in [+ (serde_json::json!(true), Some(true)),+ (serde_json::json!(false), Some(false)),+ (serde_json::Value::Null, None),+ ] {+ body["include_reasoning"] = value;+ let generate = _expect_chat_ok(body.clone())+ .into_work_params()+ .generate+ .expect("generate params");+ assert_eq!(generate.include_reasoning, expected);+ }+ body["include_reasoning"] = serde_json::json!(true);+ let generate = _expect_chat_ok(body).into_work_params().generate.unwrap();+ let wire = serde_json::to_value(&generate).unwrap();+ assert_eq!(wire["include_reasoning"], serde_json::json!(true));+ }++ #[tokio::test]+ async fn test_chat_include_reasoning_must_be_a_boolean() {+ let mut body = _chat_body_min("m");+ body["include_reasoning"] = serde_json::json!("yes");+ let err = _expect_chat_err(body).await;+ assert_eq!(err["error"]["param"], "include_reasoning");+ assert_eq!(err["error"]["code"], "invalid_request");+ }+#[test]fn test_native_generate_keeps_the_grammar_out_of_the_prompt() {let body = serde_json::json!({@@ -26963,19 +27230,22 @@ mod tests {finish_reason: Some("stop".to_string()),logprobs: None,tool_calls: None,+ reasoning_content: None,},CandidateData {text: "Beta".to_string(),finish_reason: Some("length".to_string()),logprobs: None,tool_calls: None,+ reasoning_content: None,},],executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let bytes = build_chat_completion_body("m", "req", &outcome).expect("ok");+ let bytes = build_chat_completion_body("m", "req", &outcome, false).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();let choices = v["choices"].as_array().expect("choices array");assert_eq!(choices.len(), 2);@@ -27029,19 +27299,22 @@ mod tests {"arguments": "{\"city\":\"Tokyo\"}"}})]),+ reasoning_content: None,},CandidateData {text: "plain answer".to_string(),finish_reason: Some("stop".to_string()),logprobs: None,tool_calls: None,+ reasoning_content: None,},],executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let bytes = build_chat_completion_body("m", "req-tc", &outcome).expect("ok");+ let bytes = build_chat_completion_body("m", "req-tc", &outcome, false).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();let c0 = &v["choices"][0];assert!(c0["message"]["content"].is_null());@@ -27092,12 +27365,14 @@ mod tests {finish_reason: Some("stop".to_string()),logprobs: Some(cand_lp),tool_calls: None,+ reasoning_content: None,}],executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let bytes = build_chat_completion_body("m", "req-lp", &outcome).expect("ok");+ let bytes = build_chat_completion_body("m", "req-lp", &outcome, false).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();let lps = &v["choices"][0]["logprobs"];assert!(!lps.is_null(), "candidate logprobs must surface (M4)");@@ -27477,6 +27752,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};let bytes = build_text_completion_body("m", "req-1", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -28104,6 +28380,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};let bytes = build_responses_body("m", "req-1", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -28190,9 +28467,11 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let bytes = build_chat_completion_body("Qwen/Qwen3-4B-Instruct-2507", "req-1", &outcome)- .expect("ok");+ let bytes =+ build_chat_completion_body("Qwen/Qwen3-4B-Instruct-2507", "req-1", &outcome, false)+ .expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();assert_eq!(v["object"], "chat.completion");assert_eq!(v["model"], "Qwen/Qwen3-4B-Instruct-2507");@@ -28289,8 +28568,9 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let bytes = build_chat_completion_body("m", "r", &outcome).expect("ok");+ let bytes = build_chat_completion_body("m", "r", &outcome, false).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();let lp = &v["choices"][0]["logprobs"];assert!(lp["content"].is_array(), "logprobs.content must be present");@@ -28325,12 +28605,89 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let bytes = build_chat_completion_body("m", "r", &outcome).expect("ok");+ let bytes = build_chat_completion_body("m", "r", &outcome, false).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();assert!(v["choices"][0]["logprobs"].is_null());}+ #[test]+ fn test_build_chat_completion_body_surfaces_reasoning_only_when_collected() {+ use crate::queue::streaming::CandidateData;+ let mut outcome = crate::queue::streaming::StreamOutcome {+ text: "Hi".to_string(),+ finish_reason: "stop".to_string(),+ usage: Some(crate::queue::streaming::UsageBlock {+ upstream_usage: None,+ gpu_second: None,+ images: None,+ prompt_tokens_details: None,+ prompt_tokens: 1,+ completion_tokens: 1,+ total_tokens: 2,+ }),+ attempt_id: "a".to_string(),+ ttft_ms: None,+ tpot_ms: None,+ error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,+ tool_calls: None,+ logprobs: None,+ candidates: Vec::new(),+ executed_bundle_config_hash: None,+ execution_identity_sha256: None,+ execution_binding_sha256: None,+ reasoning: Default::default(),+ };+ let bytes = build_chat_completion_body("m", "r", &outcome, true).expect("ok");+ let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert!(v["choices"][0]["message"]+ .get("reasoning_content")+ .is_none());++ outcome.reasoning.insert(0, "why".to_string());+ let bytes = build_chat_completion_body("m", "r", &outcome, true).expect("ok");+ let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(v["choices"][0]["message"]["reasoning_content"], "why");+ assert_eq!(v["choices"][0]["message"]["content"], "Hi");++ let bytes = build_chat_completion_body("m", "r", &outcome, false).expect("ok");+ let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert!(v["choices"][0]["message"]+ .get("reasoning_content")+ .is_none());++ outcome.candidates = vec![+ CandidateData {+ text: "Alpha".to_string(),+ finish_reason: Some("stop".to_string()),+ logprobs: None,+ tool_calls: None,+ reasoning_content: Some("because".to_string()),+ },+ CandidateData {+ text: "Beta".to_string(),+ finish_reason: Some("stop".to_string()),+ logprobs: None,+ tool_calls: None,+ reasoning_content: None,+ },+ ];+ let bytes = build_chat_completion_body("m", "r", &outcome, true).expect("ok");+ let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(v["choices"][0]["message"]["reasoning_content"], "because");+ assert!(v["choices"][1]["message"]+ .get("reasoning_content")+ .is_none());++ let bytes = build_chat_completion_body("m", "r", &outcome, false).expect("ok");+ let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert!(v["choices"][0]["message"]+ .get("reasoning_content")+ .is_none());+ }+/// When the worker observed tool-call deltas across the stream/// the aggregated chat-completion body surfaces them on/// ``choices[0].message.tool_calls`` with ``finish_reason:@@ -28367,8 +28724,9 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let bytes = build_chat_completion_body("m", "req-tc", &outcome).expect("ok");+ let bytes = build_chat_completion_body("m", "req-tc", &outcome, false).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();assert_eq!(v["choices"][0]["finish_reason"], "tool_calls");let msg = &v["choices"][0]["message"];@@ -28399,8 +28757,10 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let resp = build_chat_completion_body("m", "req-1", &outcome).expect_err("missing usage");+ let resp =+ build_chat_completion_body("m", "req-1", &outcome, false).expect_err("missing usage");assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);let body = axum::body::to_bytes(resp.into_body(), 16 * 1024).await@@ -29017,8 +29377,9 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};- let bytes = build_chat_completion_body("m", "req-x", &outcome).expect("ok");+ let bytes = build_chat_completion_body("m", "req-x", &outcome, false).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();// Non-streaming uses `chat.completion`, not `chat.completion.chunk`.assert_eq!(v["object"], "chat.completion");diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex 59a15cd13..a54d7d301 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -79,6 +79,10 @@ pub enum SseEndpoint {Chat {/// Whether to emit a trailing usage-only chunk before ``[DONE]``.include_usage: bool,+ /// Whether the request opted into public reasoning; a worker+ /// ``reasoning_delta`` is forwarded as ``delta.reasoning_content``+ /// only when it did.+ include_reasoning: bool,},/// SIE-native generate chunk shape.Generate,@@ -1103,12 +1107,7 @@ async fn run_sse_driver_with_lifecycle(};// Non-stale chunk arrived. Update timing trackers.- if !chunk.text_delta.is_empty()- || chunk- .tool_calls- .as_ref()- .is_some_and(|calls| !calls.is_empty())- {+ if chunk.carries_output() {if let Some(lifecycle) = lifecycle.as_mut() {lifecycle.first_token();}@@ -1264,12 +1263,15 @@ async fn run_sse_driver_with_lifecycle(&& !role_emitted.contains(&chunk.choice_index)&& !skip_forward;let event_body = match endpoint {- SseEndpoint::Chat { .. } => build_chat_chunk_event(+ SseEndpoint::Chat {+ include_reasoning, ..+ } => build_chat_chunk_event(&stream_chat_id,created,&model,&chunk,emit_role_for_this_chunk,+ include_reasoning,),SseEndpoint::Generate => build_generate_chunk_event(&chunk, &terminal_usage_extras),SseEndpoint::Completion { .. } => {@@ -1373,11 +1375,18 @@ fn build_chat_chunk_event(model: &str,chunk: &ChunkEnvelope,emit_role: bool,+ include_reasoning: bool,) -> Value {let mut delta = serde_json::Map::new();if emit_role {delta.insert("role".to_string(), json!("assistant"));}+ if include_reasoning && !chunk.reasoning_delta.is_empty() {+ delta.insert(+ "reasoning_content".to_string(),+ json!(chunk.reasoning_delta),+ );+ }if !chunk.text_delta.is_empty() {delta.insert("content".to_string(), json!(chunk.text_delta));}@@ -1536,7 +1545,7 @@ fn build_usage_only_chunk_event(terminal_extras: &[(String, Value)],) -> Option<Value> {let object = match endpoint {- SseEndpoint::Chat { include_usage } if include_usage => "chat.completion.chunk",+ SseEndpoint::Chat { include_usage, .. } if include_usage => "chat.completion.chunk",SseEndpoint::Completion { include_usage } if include_usage => "text_completion",_ => return None,};@@ -1572,7 +1581,7 @@ fn terminal_carries_usage(endpoint: SseEndpoint, chunk: &ChunkEnvelope) -> bool}match endpoint {SseEndpoint::Generate => true,- SseEndpoint::Chat { include_usage } | SseEndpoint::Completion { include_usage } => {+ SseEndpoint::Chat { include_usage, .. } | SseEndpoint::Completion { include_usage } => {include_usage}}@@ -1802,9 +1811,12 @@ async fn send_synthetic_error_chunk(executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning_delta: String::new(),};let body = match endpoint {- SseEndpoint::Chat { .. } => build_chat_chunk_event(chat_id, created, model, &chunk, false),+ SseEndpoint::Chat { .. } => {+ build_chat_chunk_event(chat_id, created, model, &chunk, false, false)+ }SseEndpoint::Completion { .. } => {build_text_completion_chunk_event(chat_id, created, model, &chunk)}@@ -2033,6 +2045,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),}}@@ -2399,6 +2412,7 @@ mod tests {for endpoint in [SseEndpoint::Chat {include_usage: true,+ include_reasoning: false,},SseEndpoint::Completion {include_usage: true,@@ -2487,6 +2501,7 @@ mod tests {for endpoint in [SseEndpoint::Chat {include_usage: false,+ include_reasoning: false,},SseEndpoint::Completion {include_usage: false,@@ -2519,6 +2534,7 @@ mod tests {for endpoint in [SseEndpoint::Chat {include_usage: false,+ include_reasoning: false,},SseEndpoint::Completion {include_usage: false,@@ -2561,6 +2577,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),}).expect("outcome receiver is live");let (durability_tx, durability_completion) = tokio::sync::oneshot::channel();@@ -2624,6 +2641,7 @@ mod tests {for endpoint in [SseEndpoint::Chat {include_usage: false,+ include_reasoning: false,},SseEndpoint::Completion {include_usage: false,@@ -2729,7 +2747,7 @@ mod tests {"bytes": [72, 105],"top_logprobs": [],})]);- let ev = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true);+ let ev = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true, false);let lp = &ev["choices"][0]["logprobs"];assert_eq!(lp["content"][0]["token"], "Hi");assert!(lp["refusal"].is_null());@@ -2739,10 +2757,33 @@ mod tests {#[test]fn test_build_chat_chunk_event_logprobs_null_when_absent() {let chunk = _delta_chunk(0, "Hi");- let ev = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true);+ let ev = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true, false);assert!(ev["choices"][0]["logprobs"].is_null());}+ /// A worker chunk carrying ``reasoning_delta`` surfaces it as+ /// ``delta.reasoning_content`` only for a request that opted in, with no+ /// ``content`` member when the chunk carried no answer text; a plain text+ /// chunk has no such member.+ #[test]+ fn test_build_chat_chunk_event_surfaces_reasoning_delta_only_when_opted_in() {+ let mut chunk = _delta_chunk(0, "");+ chunk.reasoning_delta = "why ".to_string();+ let ev = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true, true);+ let delta = &ev["choices"][0]["delta"];+ assert_eq!(delta["reasoning_content"], "why ");+ assert_eq!(delta["role"], "assistant");+ assert!(delta.get("content").is_none());++ let ev = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true, false);+ assert!(ev["choices"][0]["delta"].get("reasoning_content").is_none());++ let text = _delta_chunk(1, "Hi");+ let ev = build_chat_chunk_event("chatcmpl-1", 0, "m", &text, false, true);+ assert!(ev["choices"][0]["delta"].get("reasoning_content").is_none());+ assert_eq!(ev["choices"][0]["delta"]["content"], "Hi");+ }+fn _delta_chunk(seq: u32, text: &str) -> ChunkEnvelope {ChunkEnvelope {kind: "chunk".to_string(),@@ -2763,6 +2804,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning_delta: String::new(),}}@@ -2786,6 +2828,7 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning_delta: String::new(),}}@@ -2796,7 +2839,7 @@ mod tests {#[test]fn test_sse_chat_first_chunk_emits_role() {let chunk = _delta_chunk(0, "Hello");- let v = build_chat_chunk_event("chatcmpl-1", 1_700_000_000, "m", &chunk, true);+ let v = build_chat_chunk_event("chatcmpl-1", 1_700_000_000, "m", &chunk, true, false);assert_eq!(v["object"], "chat.completion.chunk");assert_eq!(v["id"], "chatcmpl-1");assert_eq!(v["model"], "m");@@ -2811,7 +2854,7 @@ mod tests {// choices[0].index = 2 so clients can reassemble per-candidate streams.let mut chunk = _delta_chunk(0, "B");chunk.choice_index = 2;- let v = build_chat_chunk_event("chatcmpl-1", 1_700_000_000, "m", &chunk, false);+ let v = build_chat_chunk_event("chatcmpl-1", 1_700_000_000, "m", &chunk, false, false);assert_eq!(v["choices"][0]["index"], 2);assert_eq!(v["choices"][0]["delta"]["content"], "B");}@@ -2828,7 +2871,7 @@ mod tests {chunk.finish_reason = Some("length".to_string());// done=false — this is the per-choice closure, not the global terminal.chunk.done = false;- let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);assert_eq!(v["choices"][0]["index"], 1);assert_eq!(v["choices"][0]["finish_reason"], "length");assert_eq!(v["choices"][0]["delta"]["content"], "last");@@ -2848,7 +2891,7 @@ mod tests {"bytes": [116, 111, 107],"top_logprobs": [],})]);- let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);let lps = &v["choices"][0]["logprobs"];assert!(!lps.is_null());assert_eq!(lps["content"][0]["token"], "tok");@@ -2922,7 +2965,7 @@ mod tests {#[test]fn test_sse_chat_subsequent_chunk_omits_role() {let chunk = _delta_chunk(1, " world");- let v = build_chat_chunk_event("chatcmpl-1", 1_700_000_000, "m", &chunk, false);+ let v = build_chat_chunk_event("chatcmpl-1", 1_700_000_000, "m", &chunk, false, false);let delta = &v["choices"][0]["delta"];assert!(delta.get("role").is_none(), "role must not be re-emitted");assert_eq!(delta["content"], " world");@@ -2933,7 +2976,7 @@ mod tests {#[test]fn test_sse_chat_terminal_finish_reason_stop() {let chunk = _terminal_chunk("stop", None);- let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);assert_eq!(v["choices"][0]["finish_reason"], "stop");// The terminal chunk has an empty delta — content must not// surface, but the delta object itself is still present.@@ -2943,7 +2986,7 @@ mod tests {#[test]fn test_sse_chat_terminal_finish_reason_length_preserved() {let chunk = _terminal_chunk("length", None);- let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);assert_eq!(v["choices"][0]["finish_reason"], "length");}@@ -2956,7 +2999,7 @@ mod tests {chunk.execution_binding_sha256 = Some(binding.clone());for value in [- build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false),+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false),build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),build_generate_chunk_event(&chunk, &[]),] {@@ -3003,7 +3046,7 @@ mod tests {param: Some("top_k".to_string()),retry_after_s: None,});- let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);assert_eq!(v["error"]["code"], "unsupported_field");assert_eq!(v["error"]["type"], "invalid_request_error");assert_eq!(v["error"]["param"], "top_k");@@ -3024,7 +3067,7 @@ mod tests {retry_after_s: None,});- let value = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let value = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);assert_eq!(value["error"]["code"],crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE@@ -3042,10 +3085,17 @@ mod tests {/// deltas and clean terminals keep the exact pre-existing chat shape.#[test]fn test_sse_chat_non_error_chunks_omit_request_id() {- let delta = build_chat_chunk_event("chatcmpl-1", 0, "m", &_delta_chunk(0, "Hi"), true);+ let delta =+ build_chat_chunk_event("chatcmpl-1", 0, "m", &_delta_chunk(0, "Hi"), true, false);assert!(delta.get("request_id").is_none());- let terminal =- build_chat_chunk_event("chatcmpl-1", 0, "m", &_terminal_chunk("stop", None), false);+ let terminal = build_chat_chunk_event(+ "chatcmpl-1",+ 0,+ "m",+ &_terminal_chunk("stop", None),+ false,+ false,+ );assert!(terminal.get("request_id").is_none());}@@ -3149,7 +3199,7 @@ mod tests {});let values = [- build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false),+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false),build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),build_generate_chunk_event(&chunk, &[]),];@@ -3176,7 +3226,7 @@ mod tests {});for value in [- build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false),+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false),build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),build_generate_chunk_event(&chunk, &[]),] {@@ -3195,7 +3245,7 @@ mod tests {retry_after_s: Some(12),});- let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);let completion = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);let generate = build_generate_chunk_event(&chunk, &[]);@@ -3225,7 +3275,7 @@ mod tests {chunk.error = Some(error);for value in [- build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false),+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false),build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),build_generate_chunk_event(&chunk, &[]),] {@@ -3245,7 +3295,7 @@ mod tests {retry_after_s: None,});- let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);let completion = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);let generate = build_generate_chunk_event(&chunk, &[]);@@ -3291,7 +3341,7 @@ mod tests {retry_after_s: None,});- let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);let completion = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);let generate = build_generate_chunk_event(&chunk, &[]);@@ -3315,6 +3365,7 @@ mod tests {&tx,&SseEndpoint::Chat {include_usage: false,+ include_reasoning: false,},"chatcmpl-x",1,@@ -3384,6 +3435,7 @@ mod tests {SseEndpoint::Generate,SseEndpoint::Chat {include_usage: false,+ include_reasoning: false,},SseEndpoint::Completion {include_usage: false,@@ -3514,21 +3566,21 @@ mod tests {// First chunk — must carry role.let c1 = tap.recv().await.unwrap();- let v1 = build_chat_chunk_event("chatcmpl-1", 0, "m", &c1, true);+ let v1 = build_chat_chunk_event("chatcmpl-1", 0, "m", &c1, true, false);assert_eq!(v1["choices"][0]["delta"]["role"], "assistant");assert_eq!(v1["choices"][0]["delta"]["content"], "Hello");assert!(v1["choices"][0]["finish_reason"].is_null());// Second chunk — role omitted, content only.let c2 = tap.recv().await.unwrap();- let v2 = build_chat_chunk_event("chatcmpl-1", 0, "m", &c2, false);+ let v2 = build_chat_chunk_event("chatcmpl-1", 0, "m", &c2, false, false);assert!(v2["choices"][0]["delta"].get("role").is_none());assert_eq!(v2["choices"][0]["delta"]["content"], " world");// Terminal — finish_reason populated, content empty.let c3 = tap.recv().await.unwrap();assert!(c3.done);- let v3 = build_chat_chunk_event("chatcmpl-1", 0, "m", &c3, false);+ let v3 = build_chat_chunk_event("chatcmpl-1", 0, "m", &c3, false, false);assert_eq!(v3["choices"][0]["finish_reason"], "stop");}@@ -3554,6 +3606,7 @@ mod tests {(SseEndpoint::Chat {include_usage: true,+ include_reasoning: false,},"chat.completion.chunk",),@@ -3593,6 +3646,7 @@ mod tests {let chat = build_usage_only_chunk_event(SseEndpoint::Chat {include_usage: true,+ include_reasoning: false,},"cmpl-1",1700,@@ -3639,6 +3693,7 @@ mod tests {let chat = build_usage_only_chunk_event(SseEndpoint::Chat {include_usage: true,+ include_reasoning: false,},"cmpl-1",1700,@@ -3677,6 +3732,7 @@ mod tests {for endpoint in [SseEndpoint::Chat {include_usage: false,+ include_reasoning: false,},SseEndpoint::Completion {include_usage: false,@@ -3726,6 +3782,7 @@ mod tests {for endpoint in [SseEndpoint::Chat {include_usage: true,+ include_reasoning: false,},SseEndpoint::Completion {include_usage: true,@@ -3758,7 +3815,8 @@ mod tests {let countless = _terminal_chunk("error", None);assert!(build_usage_only_chunk_event(SseEndpoint::Chat {- include_usage: true+ include_usage: true,+ include_reasoning: false,},"cmpl-1",1700,@@ -3795,6 +3853,7 @@ mod tests {let body = build_usage_only_chunk_event(SseEndpoint::Chat {include_usage: true,+ include_reasoning: false,},"cmpl-1",1700,@@ -3832,7 +3891,10 @@ mod tests {);for include_usage in [true, false] {for endpoint in [- SseEndpoint::Chat { include_usage },+ SseEndpoint::Chat {+ include_usage,+ include_reasoning: false,+ },SseEndpoint::Completion { include_usage },] {assert_eq!(terminal_carries_usage(endpoint, &terminal), include_usage);@@ -3857,6 +3919,7 @@ mod tests {SseEndpoint::Generate,SseEndpoint::Chat {include_usage: true,+ include_reasoning: false,},SseEndpoint::Completion {include_usage: true,@@ -3872,7 +3935,8 @@ mod tests {.is_none());assert!(build_usage_only_chunk_event(SseEndpoint::Chat {- include_usage: true+ include_usage: true,+ include_reasoning: false,},"cmpl-1",1700,@@ -3902,7 +3966,7 @@ mod tests {collector.apply(err_chunk);let got = tap.recv().await.unwrap();assert!(got.done);- let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &got, true);+ let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &got, true, false);assert_eq!(v["error"]["code"], "rate_limit_exceeded");assert_eq!(v["error"]["type"], "rate_limit_error");// The SIE-native generate shape would carry it too.@@ -4016,8 +4080,9 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning_delta: String::new(),};- let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true);+ let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true, false);let delta = &v["choices"][0]["delta"];// Tool-call announcement: id + function.name set, arguments empty.let tcs = delta["tool_calls"].as_array().expect("tool_calls array");@@ -4039,7 +4104,7 @@ mod tests {#[test]fn test_sse_terminal_finish_reason_tool_calls_passthrough() {let chunk = _terminal_chunk("tool_calls", None);- let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);assert_eq!(v["choices"][0]["finish_reason"], "tool_calls");}diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 87f72224c..8700fc382 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -787,6 +787,17 @@ fn patch_chat_request_schema(value: &mut Value) {"type": ["boolean", "null"],}),);+ properties.insert(+ "include_reasoning".to_string(),+ json!({+ "description": "SIE extension. `true` makes the model's reasoning public as \+ `reasoning_content` on the message and, when streaming, on each \+ delta. A model whose configuration declares no reasoning answers \+ the field with nothing. Absent or `false` keeps reasoning private; \+ `usage` is unchanged either way.",+ "type": ["boolean", "null"],+ }),+ );// response_format: {type:"text"|"json_object"|"json_schema", json_schema?:{...}}.properties.insert("response_format".to_string(),@@ -2355,6 +2366,13 @@ pub struct ChatCompletionRequest {/// applies). Absent: the serving profile decides (default on).#[serde(default, skip_serializing_if = "Option::is_none")]pub schema_in_prompt: Option<bool>,+ /// SIE extension. ``true`` makes the model's reasoning public as+ /// ``reasoning_content`` on the message and, when streaming, on each+ /// delta. A model whose configuration declares no reasoning answers the+ /// field with nothing. Absent or ``false`` keeps reasoning private;+ /// ``usage`` is unchanged either way.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub include_reasoning: Option<bool>,/// SSE streaming. When ``true``, the response is a stream of/// ``chat.completion.chunk`` events terminated by ``data: [DONE]``./// For ``n > 1``, per-``choice_index`` delta chunks include a per-choice@@ -2398,6 +2416,11 @@ pub struct ChatCompletionChoiceMessage {/// function:{name, arguments}}`` where ``arguments`` is a JSON-encoded string.#[serde(default, skip_serializing_if = "Option::is_none")]pub tool_calls: Option<Value>,+ /// The model's reasoning. Present only when the request set+ /// ``include_reasoning: true`` and the model produced any; streaming+ /// responses carry it as ``delta.reasoning_content``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reasoning_content: Option<String>,}#[derive(Debug, Serialize, Deserialize, ToSchema)]diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex 5d1392e58..c9359a066 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -441,6 +441,11 @@ pub struct GenerateParams {/// ``Some(false)`` because its caller owns the prompt.#[serde(default, skip_serializing_if = "Option::is_none")]pub schema_in_prompt: Option<bool>,+ /// Chat ``include_reasoning``: ``Some(true)`` asks the worker to publish+ /// the model's reasoning as ``reasoning_delta`` chunks. Absent keeps it+ /// private.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub include_reasoning: Option<bool>,/// Caller-supplied routing affinity hint. Highest-priority input/// to the HRW key resolution in `crate::routing::key`.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -4095,6 +4100,7 @@ impl WorkPublisher {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),};if let Some(sender) = collector.sender.take() {if sender.send(outcome).is_err() {@@ -5397,6 +5403,7 @@ impl WorkPublisher {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning: Default::default(),});if let Some(sender) = collector.sender.take() {if sender.send(outcome).is_err() {diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rsindex 68043fd70..46d7cc110 100644--- a/packages/sie_gateway/src/queue/streaming.rs+++ b/packages/sie_gateway/src/queue/streaming.rs@@ -111,6 +111,25 @@ pub struct ChunkEnvelope {/// it atomically with the full execution identity.#[serde(default, skip_serializing_if = "Option::is_none")]pub execution_binding_sha256: Option<String>,+ /// The model's reasoning for this delta, published only when the request+ /// set ``include_reasoning``. Surfaces as ``delta.reasoning_content`` on+ /// the chat stream and is concatenated into ``message.reasoning_content``+ /// for the non-streaming body.+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub reasoning_delta: String,+}++impl ChunkEnvelope {+ /// Whether the chunk carries model output: answer text, reasoning, or a+ /// tool-call delta.+ pub fn carries_output(&self) -> bool {+ !self.text_delta.is_empty()+ || !self.reasoning_delta.is_empty()+ || self+ .tool_calls+ .as_ref()+ .is_some_and(|tool_calls| !tool_calls.is_empty())+ }}fn is_zero_u32(v: &u32) -> bool {@@ -144,6 +163,10 @@ pub struct CandidateData {/// parsed for this candidate (the common case for plain text).#[serde(default, skip_serializing_if = "Option::is_none")]pub tool_calls: Option<Vec<serde_json::Value>>,+ /// This candidate's reasoning, present only when the request set+ /// ``include_reasoning`` and the model produced any.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reasoning_content: Option<String>,}/// Wire shape of one OpenAI tool-call delta. Mirrors the worker's@@ -469,6 +492,10 @@ pub struct StreamOutcome {pub executed_bundle_config_hash: Option<String>,pub execution_identity_sha256: Option<String>,pub execution_binding_sha256: Option<String>,+ /// Reasoning concatenated per ``choice_index`` from the chunks that+ /// carried ``reasoning_delta``. Empty unless the request set+ /// ``include_reasoning`` and the model produced any.+ pub reasoning: BTreeMap<u32, String>,}/// Fully-assembled tool call ready to surface on the non-streaming@@ -586,6 +613,9 @@ pub struct StreamCollector {/// requested. Snapshotted/cleared by the attempt-generation machinery/// exactly like ``chunks``.logprobs: Vec<serde_json::Value>,+ /// Reasoning concatenated per ``choice_index`` from every accepted chunk's+ /// ``reasoning_delta``. Snapshotted/cleared exactly like ``chunks``.+ reasoning: BTreeMap<u32, String>,/// Worker-origin digest latched across every accepted chunk in the current/// attempt. One absent, malformed, or mismatching chunk makes the attempt/// non-attestable while preserving ordinary streaming compatibility.@@ -640,6 +670,7 @@ struct AttemptSnapshot {chunks: Vec<(u32, String)>,tool_calls_by_index: BTreeMap<u32, AggregatedToolCall>,logprobs: Vec<serde_json::Value>,+ reasoning: BTreeMap<u32, String>,first_chunk_at: Option<Instant>,last_chunk_at: Option<Instant>,last_output_at: Option<Instant>,@@ -686,6 +717,7 @@ impl StreamCollector {chunk_tap: None,tool_calls_by_index: BTreeMap::new(),logprobs: Vec::new(),+ reasoning: BTreeMap::new(),execution_identity_sha256: None,execution_identity_consistent: true,execution_binding_sha256: None,@@ -759,6 +791,7 @@ impl StreamCollector {chunks: std::mem::take(&mut self.chunks),tool_calls_by_index: std::mem::take(&mut self.tool_calls_by_index),logprobs: std::mem::take(&mut self.logprobs),+ reasoning: std::mem::take(&mut self.reasoning),first_chunk_at: self.first_chunk_at,last_chunk_at: self.last_chunk_at,last_output_at: self.last_output_at,@@ -838,6 +871,7 @@ impl StreamCollector {self.chunks = snap.chunks;self.tool_calls_by_index = snap.tool_calls_by_index;self.logprobs = snap.logprobs;+ self.reasoning = snap.reasoning;self.first_chunk_at = snap.first_chunk_at;self.last_chunk_at = snap.last_chunk_at;self.last_output_at = snap.last_output_at;@@ -1041,12 +1075,7 @@ impl StreamCollector {// (it gates its inter-chunk timer on ``first_at.is_some()``)// throughout an active tool-call stream. Matches the SSE// driver's ``first_seen`` semantics.- let has_output = !chunk.text_delta.is_empty()- || chunk- .tool_calls- .as_ref()- .is_some_and(|tool_calls| !tool_calls.is_empty());- if has_output {+ if chunk.carries_output() {if self.first_chunk_at.is_none() {self.first_chunk_at = Some(now);}@@ -1086,6 +1115,12 @@ impl StreamCollector {if !chunk.text_delta.is_empty() {self.chunks.push((chunk.seq, chunk.text_delta));}+ if !chunk.reasoning_delta.is_empty() {+ self.reasoning+ .entry(chunk.choice_index)+ .or_default()+ .push_str(&chunk.reasoning_delta);+ }// Absorb any tool-call deltas before mutating the activity// notifier so the non-streaming aggregator (which reads@@ -1216,6 +1251,7 @@ impl StreamCollector {execution_binding_sha256: complete_execution_evidence.then(|| self.execution_binding_sha256.clone()).flatten(),+ reasoning: self.reasoning.clone(),})}}@@ -1312,9 +1348,56 @@ mod tests {executed_bundle_config_hash: None,execution_identity_sha256: None,execution_binding_sha256: None,+ reasoning_delta: String::new(),}}+ #[test]+ fn test_collector_concatenates_reasoning_per_choice_into_the_outcome() {+ let (tx, _rx) = oneshot::channel();+ let mut c = StreamCollector::new(tx, "m".to_string(), "default".to_string());+ let mut first = _make_chunk("att-A", 0, "", false);+ first.reasoning_delta = "why ".to_string();+ let mut second = _make_chunk("att-A", 1, "", false);+ second.reasoning_delta = "not".to_string();+ second.choice_index = 1;++ assert_eq!(c.apply(first), ChunkApplied::Delta);+ assert_eq!(c.apply(second), ChunkApplied::Delta);+ assert_eq!(+ c.apply(_make_chunk("att-A", 2, "Hi", false)),+ ChunkApplied::Delta+ );+ assert_eq!(+ c.apply(_make_chunk("att-A", 3, "", true)),+ ChunkApplied::Terminal+ );++ let outcome = c.build_outcome().expect("terminal");+ assert_eq!(outcome.text, "Hi");+ assert_eq!(outcome.reasoning.get(&0).map(String::as_str), Some("why "));+ assert_eq!(outcome.reasoning.get(&1).map(String::as_str), Some("not"));+ }++ #[test]+ fn test_chunk_envelope_decodes_the_worker_reasoning_delta() {+ let bytes = rmp_serde::to_vec_named(&serde_json::json!({+ "kind": "chunk", "request_id": "req-1", "attempt_id": "att-A", "seq": 0,+ "text_delta": "", "done": false, "reasoning_delta": "why",+ }))+ .expect("encode");+ let chunk: ChunkEnvelope = rmp_serde::from_slice(&bytes).expect("decode");+ assert_eq!(chunk.reasoning_delta, "why");++ let legacy = rmp_serde::to_vec_named(&serde_json::json!({+ "kind": "chunk", "request_id": "req-1", "attempt_id": "att-A", "seq": 0,+ "text_delta": "ok", "done": false,+ }))+ .expect("encode");+ let chunk: ChunkEnvelope = rmp_serde::from_slice(&legacy).expect("decode");+ assert!(chunk.reasoning_delta.is_empty());+ }+#[test]fn test_terminal_model_loading_error_chunk_builds_error_outcome() {let (tx, _rx) = oneshot::channel();@@ -1653,12 +1736,14 @@ mod tests {finish_reason: Some("stop".to_string()),logprobs: None,tool_calls: None,+ reasoning_content: None,},CandidateData {text: "two".to_string(),finish_reason: Some("length".to_string()),logprobs: None,tool_calls: None,+ reasoning_content: None,},];assert_eq!(c.apply(term), ChunkApplied::Terminal);@@ -2305,6 +2390,31 @@ mod tests {);}+ #[test]+ fn test_reasoning_only_chunk_arms_first_chunk_at() {+ let (tx, _rx) = oneshot::channel();+ let mut c = StreamCollector::new(tx, "m".to_string(), "p".to_string());+ let mut chunk = _make_chunk("att-A", 0, "", false);+ chunk.reasoning_delta = "why".to_string();+ assert_eq!(c.apply(chunk), ChunkApplied::Delta);+ assert!(c.first_chunk_at.is_some());+ assert_eq!(c.output_event_count, 1);+ }++ #[test]+ fn test_carries_output_counts_text_reasoning_and_tool_calls_only() {+ let empty = _make_chunk("att-A", 0, "", false);+ assert!(!empty.carries_output());+ assert!(_make_chunk("att-A", 0, "Hi", false).carries_output());+ assert!(_make_tool_call_chunk("att-A", 0, false).carries_output());+ let mut reasoning = empty.clone();+ reasoning.reasoning_delta = "why".to_string();+ assert!(reasoning.carries_output());+ let mut no_calls = empty;+ no_calls.tool_calls = Some(Vec::new());+ assert!(!no_calls.carries_output());+ }+/// BUG E regression: a terminal chunk re-using a ``seq`` already seen/// on a non-terminal chunk must NOT be dropped as a duplicate — the/// caller only completes on ``Terminal``, so dropping it hangs thediff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex 2439bc9ce..8823aa40b 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -1743,6 +1743,7 @@ def build_chat_body(safety_identifier: str | None = None,lora_adapter: str | None = None,stream_options: dict[str, Any] | None = None,+ include_reasoning: bool | None = None,extra_body: dict[str, Any] | None = None,) -> dict[str, Any]:"""Assemble the ``/v1/chat/completions`` request body (snake_case wire shape).@@ -1786,6 +1787,7 @@ def build_chat_body("safety_identifier": safety_identifier,"lora_adapter": lora_adapter,"stream_options": stream_options,+ "include_reasoning": include_reasoning,}body.update({key: value for key, value in optional.items() if value is not None})if extra_body:diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 9030f1ad9..9f4b85341 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -2554,6 +2554,7 @@ class SIEAsyncClient:user: str | None = None,safety_identifier: str | None = None,lora_adapter: str | None = None,+ include_reasoning: bool | None = None,gpu: str | None = None,extra_body: dict[str, Any] | None = None,wait_for_capacity: bool = True,@@ -2604,6 +2605,7 @@ class SIEAsyncClient:user=user,safety_identifier=safety_identifier,lora_adapter=lora_adapter,+ include_reasoning=include_reasoning,extra_body=extra_body,)).encode("utf-8")@@ -2709,6 +2711,7 @@ class SIEAsyncClient:safety_identifier: str | None = None,lora_adapter: str | None = None,stream_options: dict[str, Any] | None = None,+ include_reasoning: bool | None = None,gpu: str | None = None,extra_body: dict[str, Any] | None = None,wait_for_capacity: bool = True,@@ -2753,6 +2756,7 @@ class SIEAsyncClient:safety_identifier=safety_identifier,lora_adapter=lora_adapter,stream_options=stream_options,+ include_reasoning=include_reasoning,extra_body=extra_body,)).encode("utf-8")diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 1aac52475..e17daf369 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -2947,6 +2947,7 @@ class SIEClient:user: str | None = None,safety_identifier: str | None = None,lora_adapter: str | None = None,+ include_reasoning: bool | None = None,gpu: str | None = None,extra_body: dict[str, Any] | None = None,wait_for_capacity: bool = True,@@ -2998,6 +2999,7 @@ class SIEClient:user=user,safety_identifier=safety_identifier,lora_adapter=lora_adapter,+ include_reasoning=include_reasoning,extra_body=extra_body,)).encode("utf-8")@@ -3097,6 +3099,7 @@ class SIEClient:safety_identifier: str | None = None,lora_adapter: str | None = None,stream_options: dict[str, Any] | None = None,+ include_reasoning: bool | None = None,gpu: str | None = None,extra_body: dict[str, Any] | None = None,wait_for_capacity: bool = True,@@ -3143,6 +3146,7 @@ class SIEClient:safety_identifier=safety_identifier,lora_adapter=lora_adapter,stream_options=stream_options,+ include_reasoning=include_reasoning,extra_body=extra_body,)).encode("utf-8")diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex 431f3d8e6..d1b7407b7 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -788,6 +788,8 @@ class ChatMessage(TypedDict, total=False):for vision-capable generation models, base64 ``data:`` image parts);``tool_calls`` / ``tool_call_id`` are honoured on the multi-turn tool-replaypath. See the gateway schema for the canonical accepted subset.+ ``reasoning_content`` is the model's reasoning on a response message,+ present only when the request set ``include_reasoning``."""role: ChatRole@@ -795,6 +797,7 @@ class ChatMessage(TypedDict, total=False):name: strtool_call_id: strtool_calls: list[dict[str, Any]]+ reasoning_content: strclass ChatUsage(TypedDict):@@ -830,11 +833,16 @@ class ChatCompletion(TypedDict, total=False):class ChatDelta(TypedDict, total=False):- """Incremental delta emitted on each streaming chunk."""+ """Incremental delta emitted on each streaming chunk.++ ``reasoning_content`` carries the model's reasoning, present only when+ the request set ``include_reasoning``.+ """role: strcontent: strtool_calls: list[dict[str, Any]]+ reasoning_content: strclass ChatChunkChoice(TypedDict, total=False):diff --git a/packages/sie_sdk/tests/client/test_chat.py b/packages/sie_sdk/tests/client/test_chat.pyindex 4b107033b..a48fde6e0 100644--- a/packages/sie_sdk/tests/client/test_chat.py+++ b/packages/sie_sdk/tests/client/test_chat.py@@ -766,3 +766,45 @@ def test_chat_completions_extra_body_still_works_for_unknown_fields() -> None:assert sent["hypothetical_future_field"] == "future-value"assert sent["top_k"] == 99client.close()+++def test_chat_completions_sends_include_reasoning_and_keeps_reasoning_content() -> None:+ payload = {+ "id": "chatcmpl-1",+ "object": "chat.completion",+ "created": 0,+ "model": "m",+ "system_fingerprint": None,+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "Hi", "reasoning_content": "why"},+ "finish_reason": "stop",+ "logprobs": None,+ }+ ],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ }+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.post.return_value = _ok_json(payload)+ client = SIEClient("http://localhost:8080")+ out = client.chat_completions("m", [{"role": "user", "content": "hi"}], include_reasoning=True)+ assert out["choices"][0]["message"]["reasoning_content"] == "why"+ sent = json.loads(mc.return_value.post.call_args.kwargs["content"].decode("utf-8"))+ assert sent["include_reasoning"] is True+ client.close()+++def test_stream_chat_completions_yields_reasoning_content_deltas_unchanged() -> None:+ reasoning_chunk = _chat_chunk("")+ reasoning_chunk["choices"][0]["delta"] = {"role": "assistant", "reasoning_content": "why "}+ lines = _sse(reasoning_chunk, _chat_chunk("Hi", finish="stop"))+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = _FakeStream(lines=lines)+ client = SIEClient("http://localhost:8080")+ out = list(client.stream_chat_completions("m", [{"role": "user", "content": "hi"}], include_reasoning=True))+ assert [c["choices"][0]["delta"].get("reasoning_content") for c in out] == ["why ", None]+ assert [c["choices"][0]["delta"].get("content") for c in out] == [None, "Hi"]+ sent = json.loads(mc.return_value.stream.call_args.kwargs["content"].decode("utf-8"))+ assert sent["include_reasoning"] is True+ client.close()diff --git a/packages/sie_sdk/tests/client/test_sdk_requests.py b/packages/sie_sdk/tests/client/test_sdk_requests.pyindex 11ea795d7..276e03de2 100644--- a/packages/sie_sdk/tests/client/test_sdk_requests.py+++ b/packages/sie_sdk/tests/client/test_sdk_requests.py@@ -152,7 +152,7 @@ _CALLS: dict[str, tuple[str, tuple[Any, ...], dict[str, Any]]] = {"stream_chat_completions": ("stream_chat_completions",("Qwen/Qwen3-4B-Instruct-2507", [{"role": "user", "content": "Count to ten."}]),- {"max_completion_tokens": 64, "stream_options": {"include_usage": True}},+ {"max_completion_tokens": 64, "stream_options": {"include_usage": True}, "include_reasoning": True},),}diff --git a/packages/sie_server/src/sie_server/adapters/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.pyindex 8360d0722..b84df742f 100644--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py@@ -536,12 +536,29 @@ class ThinkingBlockStripper:partial tag nor its body can escape before the closing tag arrives."""- __slots__ = ("_buffer", "_close", "_inside", "_open")+ __slots__ = ("_buffer", "_close", "_inside", "_keep", "_open", "_parts")- def __init__(self, inside: bool = False, *, reasoning_format: ReasoningFormat = "qwen3") -> None:+ def __init__(+ self, inside: bool = False, *, reasoning_format: ReasoningFormat = "qwen3", keep_reasoning: bool = False+ ) -> None:self._buffer = ""self._inside = insideself._open, self._close = _REASONING_BOUNDARIES[reasoning_format]+ self._keep = keep_reasoning+ self._parts: list[tuple[str, str]] = []++ def _hide(self, text: str) -> None:+ if self._keep and text:+ if self._parts and not self._parts[-1][1]:+ self._parts[-1] = (self._parts[-1][0] + text, "")+ else:+ self._parts.append((text, ""))++ def _show(self, text: str) -> str:+ if self._keep and text:+ reasoning, visible = self._parts.pop() if self._parts else ("", "")+ self._parts.append((reasoning, visible + text))+ return text@staticmethoddef _delimiter_prefix_length(text: str, delimiters: tuple[str, ...]) -> int:@@ -560,12 +577,15 @@ class ThinkingBlockStripper:if self._inside:close_at = self._buffer.find(self._close)if close_at >= 0:+ self._hide(self._buffer[:close_at])self._buffer = self._buffer[close_at + len(self._close) :]self._inside = Falsecontinuekeep = self._delimiter_prefix_length(self._buffer, (self._close,))- self._buffer = self._buffer[-keep:] if keep else ""+ hide_upto = len(self._buffer) - keep+ self._hide(self._buffer[:hide_upto])+ self._buffer = self._buffer[hide_upto:]breakopen_at = self._buffer.find(self._open)@@ -577,7 +597,7 @@ class ThinkingBlockStripper:]if matches:marker_at, marker = min(matches, key=lambda match: match[0])- visible.append(self._buffer[:marker_at])+ visible.append(self._show(self._buffer[:marker_at]))self._buffer = self._buffer[marker_at + len(marker) :]if marker == self._open:self._inside = True@@ -587,7 +607,7 @@ class ThinkingBlockStripper:keep = self._delimiter_prefix_length(self._buffer, (self._open, self._close))emit_upto = len(self._buffer) - keep- visible.append(self._buffer[:emit_upto])+ visible.append(self._show(self._buffer[:emit_upto]))self._buffer = self._buffer[emit_upto:]break@@ -599,20 +619,34 @@ class ThinkingBlockStripper:def finish(self) -> str:"""Flush ordinary buffered text, but never truncated private reasoning."""- visible = "" if self._inside else self._buffer+ if self._inside:+ self._hide(self._buffer)+ visible = ""+ else:+ visible = self._show(self._buffer)self._buffer = ""self._inside = Falsereturn visible+ def take_parts(self) -> list[tuple[str, str]]:+ """Return ``(reasoning, text)`` runs since the previous call in output order; empty unless kept."""+ parts, self._parts = self._parts, []+ return parts-def _strip_complete_thinking_blocks(+ def take_reasoning(self) -> str:+ """Return the reasoning hidden since the previous call; empty unless kept."""+ return "".join(reasoning for reasoning, _ in self.take_parts())+++def _split_thinking_blocks(text: str,*,start_inside: bool = False,reasoning_format: ReasoningFormat = "qwen3",-) -> str:- stripper = ThinkingBlockStripper(inside=start_inside, reasoning_format=reasoning_format)- return stripper.feed(text) + stripper.finish()+) -> tuple[str, str]:+ stripper = ThinkingBlockStripper(inside=start_inside, reasoning_format=reasoning_format, keep_reasoning=True)+ visible = stripper.feed(text) + stripper.finish()+ return visible, stripper.take_reasoning()def _candidates_have_visible_text(candidates: tuple[dict[str, Any], ...] | None) -> bool:@@ -669,6 +703,7 @@ async def suppress_thinking_blocks(*,start_inside: bool = False,reasoning_format: ReasoningFormat = "qwen3",+ keep_reasoning: bool = False,) -> AsyncIterator[GenerationChunk]:"""Hide model reasoning blocks while preserving generation metadata.@@ -682,7 +717,10 @@ async def suppress_thinking_blocks(delta. ``start_inside`` covers chat templates that place the openingreasoning marker in the prompt, so generated text begins with privatereasoning and only emits the closing marker. ``reasoning_format`` selects- the boundary pair declared by the model's generation backend.+ the boundary pair declared by the model's generation backend. With+ ``keep_reasoning`` the hidden text rides on ``reasoning_delta`` (and+ ``reasoning_content`` on candidates) instead of being dropped, for a+ caller that opted into public reasoning.Closing the wrapper eagerly closes the upstream adapter iterator so clientcancellation still reaches SGLang's ``/abort_request`` cleanup.@@ -710,7 +748,7 @@ async def suppress_thinking_blocks(item = dict(candidate)text = item.get("text")if isinstance(text, str):- visible = _strip_complete_thinking_blocks(+ visible, reasoning = _split_thinking_blocks(text,start_inside=start_inside,reasoning_format=reasoning_format,@@ -719,18 +757,37 @@ async def suppress_thinking_blocks(item["text"] = visibleitem["logprobs"] = Nonehid_reasoning = True+ if keep_reasoning and reasoning:+ item["reasoning_content"] = reasoningcandidate_items.append(item)rewritten_candidates = tuple(candidate_items)state = states.setdefault(chunk.choice_index,- ThinkingBlockStripper(inside=start_inside, reasoning_format=reasoning_format),+ ThinkingBlockStripper(+ inside=start_inside, reasoning_format=reasoning_format, keep_reasoning=keep_reasoning+ ),)was_inside = state.insidevisible_delta = state.feed(chunk.text_delta)text_changed = visible_delta != chunk.text_deltaif chunk.done or chunk.finish_reason is not None:visible_delta += state.finish()+ reasoning_delta = chunk.reasoning_delta+ parts = state.take_parts()+ for reasoning, text in parts[:-1]:+ yield GenerationChunk(+ text_delta=text,+ is_first=not emitted_visible_text,+ choice_index=chunk.choice_index,+ reasoning_delta=reasoning_delta + reasoning,+ )+ reasoning_delta = ""+ visible_delta = visible_delta[len(text) :]+ emitted_visible_text = True+ emitted_meaningful_text = emitted_meaningful_text or bool(text.strip())+ if parts:+ reasoning_delta += parts[-1][0]is_first = bool(visible_delta) and not emitted_visible_textemitted_visible_text = emitted_visible_text or bool(visible_delta)@@ -743,6 +800,7 @@ async def suppress_thinking_blocks(is_first=is_first,logprobs=None if text_changed or was_inside else chunk.logprobs,candidates=rewritten_candidates,+ reasoning_delta=reasoning_delta,)if (diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex f15b2219d..f708fdf1f 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -163,6 +163,7 @@ _CUDA_CHAT_FIELDS = frozenset("logit_bias","response_format","schema_in_prompt",+ "include_reasoning","stream","tools","tool_choice",@@ -195,6 +196,7 @@ _MLX_CHAT_FIELDS = frozenset("stop","stream","stream_options",+ "include_reasoning","tools","tool_choice","parallel_tool_calls",@@ -574,7 +576,7 @@ def _validate_common_chat_body(body: dict[str, Any]) -> None:isinstance(stop, str) or (isinstance(stop, list) and all(isinstance(value, str) for value in stop))):raise _bad_request("'stop' must be a string or array of strings", param="stop")- for field in ("parallel_tool_calls", "schema_in_prompt"):+ for field in ("parallel_tool_calls", "schema_in_prompt", "include_reasoning"):if body.get(field) is not None and not isinstance(body[field], bool):raise _bad_request(f"'{field}' must be a boolean", param=field)for field in ("user", "safety_identifier"):@@ -806,6 +808,7 @@ def _prepare_chat_body(# the engine process.proxied.pop("safety_identifier", None)proxied.pop("schema_in_prompt", None)+ proxied.pop("include_reasoning", None)if proxied.get("parallel_tool_calls") is None:proxied.pop("parallel_tool_calls", None)@@ -945,6 +948,7 @@ def _prepare_mlx_body(seed: int | None,) -> dict[str, Any]:proxied = dict(body)+ proxied.pop("include_reasoning", None)proxied["model"] = adapter.mlx_reporequested_cap = max_completion_tokens if max_completion_tokens is not None else max_tokensif requested_cap is not None and requested_cap > cap:@@ -1001,6 +1005,7 @@ def _sanitize_chat_payload(reasoning_format: ReasoningFormat,states: dict[int, ThinkingBlockStripper] | None = None,terminal: bool,+ include_reasoning: bool = False,) -> dict[str, Any]:if not isinstance(payload, dict):raise ValueError("child chat response must be a JSON object")@@ -1009,6 +1014,7 @@ def _sanitize_chat_payload(if not isinstance(choices, list):return payload+ public_reasoning = include_reasoning and hide_thinking_blocksstate_map = states if states is not None else {}for position, choice in enumerate(choices):if not isinstance(choice, dict):@@ -1036,6 +1042,7 @@ def _sanitize_chat_payload(ThinkingBlockStripper(inside=initial_inside_thinking,reasoning_format=reasoning_format,+ keep_reasoning=public_reasoning,),)raw_content = container.get("content")@@ -1048,6 +1055,12 @@ def _sanitize_chat_payload(container["content"] = visibleif visible != content and "logprobs" in choice_obj:choice_obj["logprobs"] = None+ if public_reasoning:+ captured = stripper.take_reasoning()+ parsed = next((value for value in (reasoning_content, reasoning) if isinstance(value, str) and value), "")+ exposed = parsed if captured == parsed else parsed + captured+ if exposed:+ container["reasoning_content"] = exposedreturn payload@@ -1077,6 +1090,7 @@ async def _sanitize_sse_stream(slot: asyncio.Semaphore | None,tool_call_limit: int | None = None,strict_grammar: GrammarSpec | None = None,+ include_reasoning: bool = False,) -> AsyncIterator[bytes]:states: dict[int, ThinkingBlockStripper] = {}strict_contents: dict[int, list[str]] = {}@@ -1122,6 +1136,7 @@ async def _sanitize_sse_stream(reasoning_format=reasoning_format,states=states,terminal=False,+ include_reasoning=include_reasoning,)if strict_grammar is not None:violation = await _stream_strict_violation(@@ -1234,6 +1249,7 @@ async def _remote_chat_events(config: Any,adapter: GenerationAdapter,strict_grammar: GrammarSpec | None,+ include_reasoning: bool = False,) -> AsyncIterator[bytes]:states: dict[int, ThinkingBlockStripper] = {}strict_contents: dict[int, list[str]] = {}@@ -1252,6 +1268,7 @@ async def _remote_chat_events(reasoning_format=resolve_reasoning_format(config, adapter),states=states,terminal=False,+ include_reasoning=include_reasoning,)if strict_grammar is not None:violation = await _stream_strict_violation(@@ -1302,23 +1319,33 @@ async def _remote_chat_response(stream: bool,headers: dict[str, str],strict_grammar: GrammarSpec | None,+ include_reasoning: bool = False,) -> Response:try:rendered = await prepare_rendered_chat(- adapter, body, config=config, requested_model=requested_model, max_response_bytes=_MAX_CHAT_RESPONSE_BYTES+ adapter,+ body,+ config=config,+ requested_model=requested_model,+ max_response_bytes=_MAX_CHAT_RESPONSE_BYTES,+ include_reasoning=include_reasoning,)if stream:iterator = _remote_chat_events(renderedif rendered is not Noneelse adapter.chat_completion_stream(- body, requested_model=requested_model, max_response_bytes=_MAX_CHAT_RESPONSE_BYTES+ body,+ requested_model=requested_model,+ max_response_bytes=_MAX_CHAT_RESPONSE_BYTES,+ keep_reasoning=include_reasoning,),body=body,requested_model=requested_model,config=config,adapter=adapter,strict_grammar=strict_grammar,+ include_reasoning=include_reasoning,)# Decide a pre-output refusal before committing the HTTP 200.return await prefetched_sse_response(@@ -1328,7 +1355,10 @@ async def _remote_chat_response(await collect_rendered_chat(rendered)if rendered is not Noneelse await adapter.chat_completion(- body, requested_model=requested_model, max_response_bytes=_MAX_CHAT_RESPONSE_BYTES+ body,+ requested_model=requested_model,+ max_response_bytes=_MAX_CHAT_RESPONSE_BYTES,+ keep_reasoning=include_reasoning,))_check_remote_chat_usage(payload, body, config)@@ -1339,6 +1369,7 @@ async def _remote_chat_response(initial_inside_thinking=False,reasoning_format=resolve_reasoning_format(config, adapter),terminal=True,+ include_reasoning=include_reasoning,)if len(json.dumps(payload, ensure_ascii=False).encode()) > _MAX_CHAT_RESPONSE_BYTES:raise RemoteUpstreamError("upstream chat response exceeded the byte limit")@@ -1504,6 +1535,7 @@ async def _chat_completions(prepared_chat = _prepare_chat_body(body, config=config, max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, seed=seed)+ include_reasoning = body.get("include_reasoning") is Trueroute = await route_request(http_request, requested_key, span, serving_key=registry_key)@@ -1519,6 +1551,7 @@ async def _chat_completions(stream=bool(stream_opt),headers=route.headers(),strict_grammar=strict_grammar,+ include_reasoning=include_reasoning,)slot: asyncio.Semaphore | None = Nonereasoning_parser: str | None = None@@ -1632,6 +1665,7 @@ async def _chat_completions(slot=slot,tool_call_limit=tool_call_limit,strict_grammar=strict_grammar,+ include_reasoning=include_reasoning,),media_type="text/event-stream",headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no", **route.headers()},@@ -1668,6 +1702,7 @@ async def _chat_completions(initial_inside_thinking=initial_inside_thinking,reasoning_format=reasoning_format,terminal=True,+ include_reasoning=include_reasoning,)except (ValueError, TypeError, json.JSONDecodeError):logger.warning("generation child returned an invalid chat response", exc_info=True)diff --git a/packages/sie_server/src/sie_server/processors/hybrid_usage.py b/packages/sie_server/src/sie_server/processors/hybrid_usage.pyindex 89c913ba8..757cafd18 100644--- a/packages/sie_server/src/sie_server/processors/hybrid_usage.py+++ b/packages/sie_server/src/sie_server/processors/hybrid_usage.py@@ -51,7 +51,7 @@ def _candidate_texts(candidate: dict[str, Any]) -> list[str]:async def count_hybrid_usage(- chunks: AsyncIterator[GenerationChunk], count: HybridCount+ chunks: AsyncIterator[GenerationChunk], count: HybridCount, *, keep_reasoning: bool = False) -> AsyncIterator[GenerationChunk]:"""Report the worker's count on the terminal chunk and drop private reasoning.@@ -60,6 +60,7 @@ async def count_hybrid_usage(upstream's counts in ``upstream_usage``. A completion the upstream countedbut that returned no text counts as one token, and no completion countsabove ``count.completion_limit``. Any other terminal passes through.+ ``keep_reasoning`` leaves the counted reasoning on the chunks."""texts: dict[int, list[str]] = {}outcome_selected = False@@ -71,7 +72,7 @@ async def count_hybrid_usage(choice.extend((chunk.tool_call_delta.function_name or "", chunk.tool_call_delta.arguments_delta))for index, candidate in enumerate(chunk.candidates or ()):texts.setdefault(index, []).extend(_candidate_texts(candidate))- if chunk.reasoning_delta:+ if chunk.reasoning_delta and not keep_reasoning:if _only_reasoning(chunk):continuechunk = replace(chunk, reasoning_delta="")diff --git a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.pyindex 3c5db183b..f48643145 100644--- a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py+++ b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py@@ -61,6 +61,7 @@ async def prepare_rendered_chat(config: ModelConfig,requested_model: str,max_response_bytes: int,+ include_reasoning: bool = False,) -> AsyncIterator[dict[str, Any]] | None:"""Prefer a usable onboarded template; otherwise select declared chat."""body = dict(body)@@ -159,6 +160,7 @@ async def prepare_rendered_chat(chunks,start_inside=isinstance(adapter, OpenAIUpstreamAdapter) and reasoning_starts_in_prompt(prompt, reasoning),reasoning_format=reasoning,+ keep_reasoning=include_reasoning,)if tools:chunks = parse_tool_call_stream(@@ -197,6 +199,8 @@ async def _events(if chunk.error_code or chunk.finish_reason == "cancelled":raise RemoteUpstreamError("upstream rendered chat did not finish successfully")delta: dict[str, Any] = {}+ if chunk.reasoning_delta:+ delta["reasoning_content"] = chunk.reasoning_deltaif chunk.text_delta:delta["content"] = chunk.text_deltaif chunk.tool_call_delta is not None:@@ -244,6 +248,7 @@ async def _events(async def collect_rendered_chat(events: AsyncIterator[dict[str, Any]]) -> dict[str, Any]:"""Assemble the same normalized events for a buffered chat request."""text: list[str] = []+ reasoning: list[str] = []tools: dict[int, dict[str, Any]] = {}final = Nonetry:@@ -251,6 +256,7 @@ async def collect_rendered_chat(events: AsyncIterator[dict[str, Any]]) -> dict[schoice = event["choices"][0]delta = choice["delta"]text.append(delta.get("content", ""))+ reasoning.append(delta.get("reasoning_content", ""))for fragment in delta.get("tool_calls") or []:tool = tools.setdefault(fragment["index"], {"id": "", "type": "function", "function": {"name": "", "arguments": ""}}@@ -263,6 +269,8 @@ async def collect_rendered_chat(events: AsyncIterator[dict[str, Any]]) -> dict[sif final is None:raise RemoteUpstreamError("upstream rendered chat omitted its terminal chunk")message: dict[str, Any] = {"role": "assistant", "content": "".join(text) or None}+ if any(reasoning):+ message["reasoning_content"] = "".join(reasoning)if tools:message["tool_calls"] = [tools[index] for index in sorted(tools)]return {diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 4c46e9ce4..ede015ecc 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -821,6 +821,10 @@ class _GenerateRequestParams:# Multi-LoRA — served-name of the adapter to apply (passed to SGLang as# ``sampling_params.lora_path``). ``None`` → base model.lora_adapter: str | None = None+ # Chat ``include_reasoning``: publish the model's reasoning as+ # ``reasoning_delta`` chunks instead of dropping it. Honoured only for a+ # model whose config declares reasoning.+ include_reasoning: bool = Falsedef _remote_chat_parameters(params: _GenerateRequestParams) -> dict[str, Any]:@@ -1881,6 +1885,7 @@ class StreamingProcessor:)returnsuppress_thinking = thinking_blocks_must_be_hidden(config)+ keep_reasoning = params.include_reasoning and suppress_thinkingreasoning_format = resolve_reasoning_format(config, adapter)# Resolve ``tool_choice`` mode up front. When the caller set@@ -2197,7 +2202,7 @@ class StreamingProcessor:remote_body,requested_model=model_id,context_length=config.tasks.generate.context_length,- keep_reasoning=hybrid_count is not None,+ keep_reasoning=hybrid_count is not None or keep_reasoning,)preflight_result = Noneelse:@@ -2301,6 +2306,7 @@ class StreamingProcessor:suppress_thinking=suppress_thinking,thinking_starts_in_prompt=thinking_starts_in_prompt,reasoning_format=reasoning_format,+ keep_reasoning=keep_reasoning,grammar=effective_grammar,tools=effective_tools,enable_tool_parser=enable_tool_parser,@@ -2346,6 +2352,7 @@ class StreamingProcessor:suppress_thinking: bool = False,thinking_starts_in_prompt: bool = False,reasoning_format: ReasoningFormat = "qwen3",+ keep_reasoning: bool = False,grammar: GrammarSpec | None = None,tools: tuple[dict[str, Any], ...] | None = None,enable_tool_parser: bool | None = None,@@ -2389,12 +2396,13 @@ class StreamingProcessor:else adapter.generate_with_preflight(gen_kwargs, preflight_result))if hybrid_count is not None:- chunks_iter = count_hybrid_usage(chunks_iter, hybrid_count)+ chunks_iter = count_hybrid_usage(chunks_iter, hybrid_count, keep_reasoning=keep_reasoning)if suppress_thinking:chunks_iter = suppress_thinking_blocks(chunks_iter,start_inside=thinking_starts_in_prompt,reasoning_format=reasoning_format,+ keep_reasoning=keep_reasoning,)# OpenAI tools: when enabled, wrap the adapter iterator with the# tool-call parser so ``<tool_call>{...}</tool_call>`` blocks@@ -2431,6 +2439,11 @@ class StreamingProcessor:# (no cross-candidate text coalescing).multi_candidate_stream = bool(stream) and n is not None and n > 1pending_text: list[str] = []+ # Public reasoning, coalesced per choice like text. A chunk's reasoning+ # precedes its text, so pending reasoning is published ahead of+ # pending text and new reasoning first flushes the text before it.+ pending_reasoning: list[str] = []+ pending_reasoning_choice = 0# OpenAI per-token logprob entries accumulated alongside# ``pending_text`` and flushed in the same coalesced chunk. The# adapter aligns each entry with the tokens in ``text_delta``.@@ -2473,6 +2486,27 @@ class StreamingProcessor:stream error)."""nonlocal seq, pending_count, last_flush_ts, first_text_published+ if pending_reasoning:+ reasoning_payload = _encode_chunk(+ kind="chunk",+ request_id=request_id,+ attempt_id=attempt_id,+ seq=seq,+ text_delta="",+ done=False,+ choice_index=pending_reasoning_choice,+ reasoning_delta="".join(pending_reasoning),+ )+ try:+ await _wait_for(chunk_queue.put((reasoning_payload, False)), timeout=_CHUNK_PUT_TIMEOUT_S)+ except (asyncio.QueueFull, TimeoutError):+ return False+ seq += 1+ pending_reasoning.clear()+ last_flush_ts = time.monotonic()+ if not pending_text:+ pending_count = 0+ return Trueif not pending_text and not progress:return Truetext = "".join(pending_text)@@ -2498,6 +2532,16 @@ class StreamingProcessor:last_flush_ts = time.monotonic()return True+ async def _pend_reasoning(chunk: GenerationChunk) -> bool:+ nonlocal pending_count, pending_reasoning_choice+ other_choice = bool(pending_reasoning) and chunk.choice_index != pending_reasoning_choice+ if (pending_text or other_choice) and not await _flush_pending():+ return False+ pending_reasoning_choice = chunk.choice_index+ pending_reasoning.append(chunk.reasoning_delta)+ pending_count += max(1, len(chunk.reasoning_delta))+ return True+next_task: asyncio.Task[GenerationChunk] | None = Nonecancel_task: asyncio.Task[bool] | None = Nonetry:@@ -2672,6 +2716,7 @@ class StreamingProcessor:choice_index=chunk.choice_index,logprobs=list(chunk.logprobs) if chunk.logprobs else None,tool_call_delta=chunk.tool_call_delta,+ reasoning_delta=chunk.reasoning_delta,)# H6: seq advances ONLY after the put succeeds. Per-choice# deltas are required content chunks: a dropped delta@@ -2695,6 +2740,11 @@ class StreamingProcessor:if chunk.done:# Flush any coalesced text before the terminal chunk.+ if chunk.reasoning_delta and not await _pend_reasoning(chunk):+ _record_failure()+ transport_failure_published = True+ terminal_sent = await self._enqueue_transport_failure(chunk_queue, request_id, attempt_id, seq)+ breakif chunk.text_delta:pending_text.append(chunk.text_delta)pending_count += max(1, len(chunk.text_delta))@@ -2798,6 +2848,11 @@ class StreamingProcessor:continue# Non-terminal delta: accumulate, flush on time/count.+ if chunk.reasoning_delta and not await _pend_reasoning(chunk):+ _record_failure()+ transport_failure_published = True+ terminal_sent = await self._enqueue_transport_failure(chunk_queue, request_id, attempt_id, seq)+ breakif chunk.text_delta:pending_text.append(chunk.text_delta)pending_count += max(1, len(chunk.text_delta))@@ -3457,6 +3512,10 @@ class StreamingProcessor:if schema_in_prompt_raw is not Noneelse (config is None or profile_schema_in_prompt(config)))+ include_reasoning_raw = params.get("include_reasoning")+ if include_reasoning_raw is not None and not isinstance(include_reasoning_raw, bool):+ return _ValidationError(code="invalid_request", message="'include_reasoning' must be a boolean")+ include_reasoning = bool(include_reasoning_raw)# OpenAI ``seed`` / ``logit_bias`` / ``logprobs`` / ``top_logprobs``# round-trips. Gateway is the authority for shape validation@@ -3593,6 +3652,7 @@ class StreamingProcessor:best_of=best_of,stream=stream,lora_adapter=lora_adapter,+ include_reasoning=include_reasoning,)async def _get_tokenizer(self, model_id: str) -> TokenizerLike:@@ -4593,6 +4653,7 @@ def _encode_chunk(logprobs: list[dict[str, Any]] | None = None,candidates: list[dict[str, Any]] | None = None,choice_index: int = 0,+ reasoning_delta: str = "",) -> bytes:"""Encode one chunk envelope as msgpack bytes.@@ -4668,6 +4729,8 @@ def _encode_chunk(if choice_index:# Streaming multi-candidate: the candidate ordinal this delta belongs to.payload["choice_index"] = choice_index+ if reasoning_delta:+ payload["reasoning_delta"] = reasoning_deltaif tool_call_delta is not None:function_block: dict[str, Any] = {}if tool_call_delta.function_name is not None:diff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.pyindex 85bd1569f..fefa16ba1 100644--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py@@ -559,6 +559,8 @@ async def _parse_tool_call_stream_impl(yield chunkcontinueidx = chunk.choice_index+ if chunk.reasoning_delta:+ yield GenerationChunk(text_delta="", choice_index=idx, reasoning_delta=chunk.reasoning_delta)state = _state(idx)incoming = chunk.text_deltadiff --git a/packages/sie_server/tests/adapters/test_generation_base.py b/packages/sie_server/tests/adapters/test_generation_base.pyindex 9bc49231c..a2d755695 100644--- a/packages/sie_server/tests/adapters/test_generation_base.py+++ b/packages/sie_server/tests/adapters/test_generation_base.py@@ -671,3 +671,61 @@ async def test_collect_generation_preserves_selected_result_when_close_fails() -assert result.text == "done"assert source.close_calls == 1+++async def test_suppress_thinking_blocks_keeps_reasoning_only_when_asked() -> None:+ raw = "<think>private chain</think>Visible answer"+ deltas = [GenerationChunk(text_delta=char, is_first=index == 0) for index, char in enumerate(raw)]+ terminal = GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ prompt_tokens=3,+ completion_tokens=11,+ candidates=({"text": "<think>why</think>one", "finish_reason": "stop", "logprobs": None},),+ )++ kept = [chunk async for chunk in suppress_thinking_blocks(_chunks(*deltas, terminal), keep_reasoning=True)]+ dropped = [chunk async for chunk in suppress_thinking_blocks(_chunks(*deltas, terminal))]++ assert "".join(chunk.text_delta for chunk in kept) == "Visible answer"+ assert "".join(chunk.reasoning_delta for chunk in kept) == "private chain"+ assert kept[-1].candidates == (+ {"text": "one", "finish_reason": "stop", "logprobs": None, "reasoning_content": "why"},+ )+ assert "".join(chunk.text_delta for chunk in dropped) == "Visible answer"+ assert all(not chunk.reasoning_delta for chunk in dropped)+ assert dropped[-1].candidates == ({"text": "one", "finish_reason": "stop", "logprobs": None},)+++async def test_suppress_thinking_blocks_keeps_truncated_reasoning_when_asked() -> None:+ source = _chunks(+ GenerationChunk(text_delta="<think>cut off mid", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="length", prompt_tokens=3, completion_tokens=4),+ )++ kept = [chunk async for chunk in suppress_thinking_blocks(source, keep_reasoning=True)]++ assert "".join(chunk.reasoning_delta for chunk in kept) == "cut off mid"+ assert "".join(chunk.text_delta for chunk in kept) == ""+ assert kept[-1].error_code == "empty_model_output"+++async def test_suppress_thinking_blocks_keeps_text_before_the_reasoning_that_follows_it() -> None:+ source = _chunks(+ GenerationChunk(text_delta="Hello <think>x</think> world", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=3, completion_tokens=8),+ )++ kept = [chunk async for chunk in suppress_thinking_blocks(source, keep_reasoning=True)]++ assert [(chunk.reasoning_delta, chunk.text_delta) for chunk in kept if not chunk.done] == [+ ("", "Hello "),+ ("x", " world"),+ ]+ assert [chunk.is_first for chunk in kept if not chunk.done] == [True, False]+ assert kept[-1].done+ assert kept[-1].error_code is Nonediff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.pyindex e7df2eb5e..0b25ccd3c 100644--- a/packages/sie_server/tests/api/test_openai_local.py+++ b/packages/sie_server/tests/api/test_openai_local.py@@ -2109,3 +2109,312 @@ def test_cuda_chat_response_format_without_its_grammar_profile_is_rejected(monkeassert error["param"] == "response_format"assert "'no-spec'" in error["message"]registry.get.assert_not_called()+++# -- /v1/chat/completions include_reasoning ---------------------------------+++def _reasoning_child_payload(content: str, *, reasoning_content: str | None = None) -> dict[str, Any]:+ message: dict[str, Any] = {"role": "assistant", "content": content}+ if reasoning_content is not None:+ message["reasoning_content"] = reasoning_content+ return {+ "id": "chatcmpl-test",+ "object": "chat.completion",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [+ {+ "index": 0,+ "message": message,+ "logprobs": {"content": [{"token": "Visible", "logprob": -0.1, "bytes": None, "top_logprobs": []}]},+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},+ }+++def _stream_event(delta: dict[str, Any], *, finish_reason: str | None = None) -> dict[str, Any]:+ return {+ "id": "chatcmpl-stream",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],+ }+++ ("declares_reasoning", "include_reasoning", "expected"),+ [(True, True, "private chain"), (True, False, None), (False, True, None)],+)+def test_cuda_chat_blocking_publishes_parser_reasoning_only_when_asked(+ monkeypatch: pytest.MonkeyPatch, declares_reasoning: bool, include_reasoning: bool, expected: str | None+) -> None:+ seen: dict[str, Any] = {}++ def _handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return httpx.Response(200, json=_reasoning_child_payload("Visible answer", reasoning_content="private chain"))++ client, _ = _cuda_chat_client(+ monkeypatch,+ _handler,+ reasoning_parser="qwen3",+ chat_template_kwargs={"enable_thinking": True} if declares_reasoning else {},+ )+ body: dict[str, Any] = {"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hello"}]}+ if include_reasoning:+ body["include_reasoning"] = True++ response = client.post("/v1/chat/completions", json=body)++ assert response.status_code == 200+ assert "include_reasoning" not in seen["body"]+ payload = response.json()+ assert payload["choices"][0]["message"]["content"] == "Visible answer"+ assert payload["choices"][0]["message"].get("reasoning_content") == expected+ assert payload["choices"][0]["logprobs"] is None+ assert payload["usage"]["completion_tokens"] == 4++[email protected]("parser", [False, True])+def test_cuda_chat_stream_publishes_split_reasoning_when_asked(monkeypatch: pytest.MonkeyPatch, parser: bool) -> None:+ reasoning_deltas = (+ [+ _stream_event({"reasoning_content": "private ", "content": ""}),+ _stream_event({"reasoning_content": "chain"}),+ _stream_event({"content": "Visible answer"}),+ ]+ if parser+ else [+ _stream_event({"content": "private chain</thi"}),+ _stream_event({"content": "nk>Visible answer"}),+ ]+ )+ events = [+ _stream_event({"role": "assistant", "content": ""}),+ *reasoning_deltas,+ _stream_event({}, finish_reason="stop"),+ ]+ wire = b"".join(f"data: {json.dumps(event)}\n\n".encode() for event in events) + b"data: [DONE]\n\n"+ upstream_stream = _ChunkedAsyncStream([wire[:37], wire[37:121], wire[121:]])++ def _handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, stream=upstream_stream, headers={"content-type": "text/event-stream"})++ client, _ = _cuda_chat_client(+ monkeypatch,+ _handler,+ reasoning_parser="qwen3" if parser else None,+ chat_template_kwargs={"enable_thinking": True},+ )+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3-0.6B:thinking",+ "messages": [{"role": "user", "content": "Hello"}],+ "max_tokens": 8,+ "stream": True,+ "include_reasoning": True,+ },+ )++ assert response.status_code == 200+ data_lines = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]+ assert data_lines[-1] == "[DONE]"+ deltas = [json.loads(line)["choices"][0]["delta"] for line in data_lines[:-1]]+ assert "".join(delta.get("content", "") for delta in deltas) == "Visible answer"+ assert "".join(delta.get("reasoning_content", "") for delta in deltas) == "private chain"+ assert "</think>" not in response.text+ assert upstream_stream.closed is True+++def test_mlx_chat_publishes_raw_tag_reasoning_when_asked(monkeypatch: pytest.MonkeyPatch) -> None:+ seen: dict[str, Any] = {}++ def _handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-mlx",+ "object": "chat.completion",+ "created": 1,+ "model": "mlx-community/Qwen3.5-4B-4bit",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "<think>private default reasoning</think>Visible answer",+ },+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 3, "completion_tokens": 9, "total_tokens": 12},+ },+ )++ client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": "Hello"}],+ "include_reasoning": True,+ },+ )++ assert response.status_code == 200+ assert "include_reasoning" not in seen["body"]+ message = response.json()["choices"][0]["message"]+ assert message["content"] == "Visible answer"+ assert message["reasoning_content"] == "private default reasoning"+++def test_chat_rejects_a_non_boolean_include_reasoning(monkeypatch: pytest.MonkeyPatch) -> None:+ client, registry = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(500))++ response = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hi"}], "include_reasoning": "yes"},+ )++ assert response.status_code == 400+ assert response.json()["error"]["param"] == "include_reasoning"+ registry.get.assert_not_called()+++def _sse_wire(events: list[dict[str, Any]]) -> bytes:+ return b"".join(f"data: {json.dumps(event)}\n\n".encode() for event in events) + b"data: [DONE]\n\n"+++def _sse_deltas(response_text: str) -> list[dict[str, Any]]:+ lines = [line.removeprefix("data: ") for line in response_text.splitlines() if line.startswith("data: ")]+ assert lines[-1] == "[DONE]"+ return [json.loads(line)["choices"][0]["delta"] for line in lines[:-1]]+++ ("parsed", "content", "expected_reasoning", "expected_content"),+ [+ ("A", "x<think>B</think>y", "AB", "xy"),+ ("same", "<think>same</think>answer", "same", "answer"),+ ],+)+def test_cuda_chat_answers_parser_and_raw_tag_reasoning_without_losing_either(+ monkeypatch: pytest.MonkeyPatch, parsed: str, content: str, expected_reasoning: str, expected_content: str+) -> None:+ client, _ = _cuda_chat_client(+ monkeypatch,+ lambda _request: httpx.Response(200, json=_reasoning_child_payload(content, reasoning_content=parsed)),+ reasoning_parser="qwen3",+ chat_template_kwargs={"enable_thinking": True},+ )++ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3-0.6B",+ "messages": [{"role": "user", "content": "Hello"}],+ "include_reasoning": True,+ },+ )++ assert response.status_code == 200+ message = response.json()["choices"][0]["message"]+ assert message["reasoning_content"] == expected_reasoning+ assert message["content"] == expected_content++[email protected]("stream", [False, True])+def test_cuda_chat_with_tools_answers_reasoning_beside_the_calls(monkeypatch: pytest.MonkeyPatch, stream: bool) -> None:+ call = {"id": "call-1", "type": "function", "function": {"name": "lookup", "arguments": '{"q":"x"}'}}+ seen: dict[str, Any] = {}++ def _handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ if not stream:+ payload = _reasoning_child_payload("", reasoning_content="need a lookup")+ payload["choices"][0]["message"].update(content=None, tool_calls=[call])+ payload["choices"][0]["finish_reason"] = "tool_calls"+ return httpx.Response(200, json=payload)+ wire = _sse_wire(+ [+ _stream_event({"role": "assistant", "content": ""}),+ _stream_event({"reasoning_content": "need a lookup"}),+ _stream_event({"tool_calls": [{"index": 0, **call}]}),+ _stream_event({}, finish_reason="tool_calls"),+ ]+ )+ return httpx.Response(200, stream=_ChunkedAsyncStream([wire]), headers={"content-type": "text/event-stream"})++ client, _ = _cuda_chat_client(+ monkeypatch, _handler, reasoning_parser="qwen3", chat_template_kwargs={"enable_thinking": True}+ )+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3-0.6B",+ "messages": [{"role": "user", "content": "Look it up"}],+ "tools": [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}],+ "stream": stream,+ "include_reasoning": True,+ },+ )++ assert response.status_code == 200+ assert "include_reasoning" not in seen["body"]+ assert seen["body"]["tools"][0]["function"]["name"] == "lookup"+ if stream:+ deltas = _sse_deltas(response.text)+ assert "".join(delta.get("reasoning_content", "") for delta in deltas) == "need a lookup"+ assert [delta["tool_calls"][0]["function"]["name"] for delta in deltas if delta.get("tool_calls")] == ["lookup"]+ else:+ message = response.json()["choices"][0]["message"]+ assert message["reasoning_content"] == "need a lookup"+ assert message["tool_calls"][0]["function"] == call["function"]+ assert response.json()["choices"][0]["finish_reason"] == "tool_calls"++[email protected]("include_reasoning", [False, True])+def test_mlx_chat_stream_publishes_raw_tag_reasoning_only_when_asked(+ monkeypatch: pytest.MonkeyPatch, include_reasoning: bool+) -> None:+ wire = _sse_wire(+ [+ _stream_event({"role": "assistant", "content": ""}),+ _stream_event({"content": "<think>private "}),+ _stream_event({"content": "default reasoning</th"}),+ _stream_event({"content": "ink>Visible answer"}),+ _stream_event({}, finish_reason="stop"),+ ]+ )+ seen: dict[str, Any] = {}++ def _handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return httpx.Response(+ 200, stream=_ChunkedAsyncStream([wire[:61], wire[61:]]), headers={"content-type": "text/event-stream"}+ )++ client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": "Hello"}],+ "stream": True,+ "include_reasoning": include_reasoning,+ },+ )++ assert response.status_code == 200+ assert "include_reasoning" not in seen["body"]+ deltas = _sse_deltas(response.text)+ assert "".join(delta.get("content", "") for delta in deltas) == "Visible answer"+ reasoning = "".join(delta.get("reasoning_content", "") for delta in deltas)+ assert reasoning == ("private default reasoning" if include_reasoning else "")+ assert "<think>" not in response.textdiff --git a/packages/sie_server/tests/api/test_remote_chat.py b/packages/sie_server/tests/api/test_remote_chat.pyindex 45d538987..d36dd0d42 100644--- a/packages/sie_server/tests/api/test_remote_chat.py+++ b/packages/sie_server/tests/api/test_remote_chat.py@@ -411,6 +411,40 @@ def test_remote_reasoning_is_not_exposed_in_logprobs(remote_chat: tuple, streamiassert "PRIVATE_REASONING" not in response.text[email protected]("streaming", [False, True])[email protected]("declares_reasoning", [False, True])+def test_include_reasoning_publishes_remote_reasoning_only_for_a_reasoning_model(+ remote_chat: tuple, streaming: bool, declares_reasoning: bool+) -> None:+ client, _, config, _ = remote_chat+ if declares_reasoning:+ config.tasks.generate.chat_template_kwargs = {"enable_thinking": True}+ raw = completion()+ raw["choices"][0]["message"]["reasoning_content"] = "PRIVATE_REASONING"+ if streaming:+ chunks = events()+ chunks[0]["choices"][0]["delta"]["reasoning_content"] = "PRIVATE_REASONING"+ answer_with(+ remote_chat, httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=ChatStream(chunks))+ )+ else:+ answer_with(remote_chat, json_response(200, raw))++ response = client.post("/v1/chat/completions", json={**BODY, "stream": streaming, "include_reasoning": True})++ assert response.status_code == 200+ if streaming:+ payloads = [+ json.loads(line.removeprefix("data: "))+ for line in response.text.splitlines()+ if line.startswith("data: ") and not line.endswith("[DONE]")+ ]+ reasoning = "".join(p["choices"][0]["delta"].get("reasoning_content", "") for p in payloads if p["choices"])+ else:+ reasoning = response.json()["choices"][0]["message"].get("reasoning_content", "")+ assert reasoning == ("PRIVATE_REASONING" if declares_reasoning else "")++@pytest.mark.parametrize("status", [400, 503])def test_native_remote_stream_refusal_precedes_http_success(remote_chat: tuple, status: int) -> None:client, _, config, requests = remote_chat@@ -827,3 +861,51 @@ def test_invalid_response_format_fails_before_template_load_or_dispatch(remote_cassert response.json()["error"]["param"] == "response_format"assert not requestsregistry.start_load_async.assert_not_called()++[email protected]("remote_chat", ["openai"], indirect=True)[email protected]("stream", [False, True])[email protected]("include_reasoning", [False, True])+def test_onboarded_direct_chat_answers_rendered_reasoning_only_when_asked(+ remote_chat, monkeypatch: pytest.MonkeyPatch, stream: bool, include_reasoning: bool+) -> None:+ client, _, config, _ = remote_chat+ data = config.model_dump()+ data.update(remote_backed=False, hf_id="onboarded/model", hf_revision="a" * 40)+ data["profiles"]["default"]["adapter_options"]["runtime"] = {}+ data["tasks"]["generate"]["chat_template_kwargs"] = {"enable_thinking": True}+ client.app.state.registry.get_config.return_value = ModelConfig.model_validate(data)+ monkeypatch.setattr(+ remote_chat_prompt,+ "_tokenizer",+ lambda *args: SimpleNamespace(+ chat_template="template", apply_chat_template=lambda *args, **kwargs: "owned prompt<think>"+ ),+ )+ upstream_stream = ChatStream(+ [+ {"choices": [{"index": 0, "text": "PRIVATE_REASONING</think>answer", "finish_reason": None}]},+ {"choices": [{"index": 0, "text": "", "finish_reason": "stop"}], "usage": USAGE},+ "[DONE]",+ ]+ )+ answer_with(remote_chat, httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=upstream_stream))++ response = client.post(+ "/v1/chat/completions",+ json={**BODY, "max_tokens": 32, "stream": stream, "include_reasoning": include_reasoning},+ )++ assert response.status_code == 200+ if stream:+ payloads = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: {")]+ deltas = [payload["choices"][0]["delta"] for payload in payloads if payload["choices"]]+ reasoning = "".join(delta.get("reasoning_content", "") for delta in deltas)+ content = "".join(delta.get("content") or "" for delta in deltas)+ else:+ message = response.json()["choices"][0]["message"]+ reasoning, content = message.get("reasoning_content", ""), message["content"]+ assert content == "answer"+ assert reasoning == ("PRIVATE_REASONING" if include_reasoning else "")+ assert "think>" not in response.text+ assert upstream_stream.closeddiff --git a/packages/sie_server/tests/processors/test_hybrid_usage.py b/packages/sie_server/tests/processors/test_hybrid_usage.pyindex 69d8ada5b..5ee64a085 100644--- a/packages/sie_server/tests/processors/test_hybrid_usage.py+++ b/packages/sie_server/tests/processors/test_hybrid_usage.py@@ -410,3 +410,19 @@ async def test_cancellation_closes_the_counted_upstream_chat(hybrid: tuple) -> Nassert chunks[-1]["finish_reason"] == "cancelled"assert "usage" not in chunks[-1]assert stream.closed+++async def test_keep_reasoning_counts_it_and_leaves_it_on_the_chunks() -> None:+ source = _Chunks(+ [+ GenerationChunk(text_delta="", reasoning_delta="think one two "),+ GenerationChunk(text_delta="answer here", is_first=True),+ _terminal(),+ ]+ )++ out = [chunk async for chunk in count_hybrid_usage(source, _count(), keep_reasoning=True)]++ assert [chunk.reasoning_delta for chunk in out] == ["think one two ", "", ""]+ assert [chunk.text_delta for chunk in out] == ["", "answer here", ""]+ assert out[-1].completion_tokens == 5diff --git a/packages/sie_server/tests/processors/test_remote_chat.py b/packages/sie_server/tests/processors/test_remote_chat.pyindex aaf2973c0..63681ec24 100644--- a/packages/sie_server/tests/processors/test_remote_chat.py+++ b/packages/sie_server/tests/processors/test_remote_chat.py@@ -627,3 +627,76 @@ async def test_onboarded_native_sie_preserves_already_suppressed_answer(remote:assert "".join(chunk.get("text_delta", "") for chunk in chunks) == "answer"assert chunks[-1]["finish_reason"] == "stop"assert requests[0].url.path.endswith("/generate/operator__model")++[email protected]("declares_reasoning", [False, True])+async def test_include_reasoning_publishes_upstream_reasoning_only_for_a_reasoning_model(+ remote: tuple, declares_reasoning: bool+) -> None:+ _adapter, proc, _nc, _requests = remote+ if declares_reasoning:+ config_data = proc._registry.get_config(MODEL).model_dump()+ config_data["tasks"]["generate"]["chat_template_kwargs"] = {"enable_thinking": True}+ proc._registry.get_config.return_value = ModelConfig.model_validate(config_data)+ frame = choice("")+ frame["choices"][0]["delta"]["reasoning_content"] = "PRIVATE"+ respond(remote, frames=[frame, *events()])++ msg, chunks = await run(remote, include_reasoning=True)++ assert "".join(chunk.get("text_delta", "") for chunk in chunks) == "answer"+ reasoning = "".join(chunk.get("reasoning_delta", "") for chunk in chunks)+ assert reasoning == ("PRIVATE" if declares_reasoning else "")+ assert chunks[-1]["usage"] == USAGE+ msg.ack.assert_awaited_once()+++def _declare_reasoning(proc: StreamingProcessor) -> None:+ config_data = proc._registry.get_config(MODEL).model_dump()+ config_data["tasks"]["generate"]["chat_template_kwargs"] = {"enable_thinking": True}+ proc._registry.get_config.return_value = ModelConfig.model_validate(config_data)++[email protected]("streaming", [False, True])+async def test_include_reasoning_keeps_each_choice_reasoning_on_its_own_choice(remote: tuple, streaming: bool) -> None:+ _adapter, proc, _nc, _requests = remote+ _declare_reasoning(proc)+ if streaming:+ frames: list[dict | str] = []+ for index, (reasoning, text, finish) in enumerate((("R0", "first", "stop"), ("R1", "second", "length"))):+ frame = choice(text, index=index)+ frame["choices"][0]["delta"]["reasoning_content"] = reasoning+ frames += [frame, choice("", index=index, finish=finish)]+ respond(remote, frames=[*frames, {"choices": [], "usage": USAGE}, "[DONE]"])+ else:+ respond(+ remote,+ payload={+ "choices": [+ {+ "index": 1,+ "message": {"role": "assistant", "content": "second", "reasoning_content": "R1"},+ "finish_reason": "length",+ },+ {+ "index": 0,+ "message": {"role": "assistant", "content": "first", "reasoning_content": "R0"},+ "finish_reason": "stop",+ },+ ],+ "usage": USAGE,+ },+ )++ msg, chunks = await run(remote, n=2, stream=streaming, include_reasoning=True)++ reasoning: dict[int, str] = {}+ for chunk in chunks:+ if chunk.get("reasoning_delta"):+ index = chunk.get("choice_index", 0)+ reasoning[index] = reasoning.get(index, "") + chunk["reasoning_delta"]+ assert reasoning == {0: "R0", 1: "R1"}+ if not streaming:+ assert [item["text"] for item in chunks[-1]["candidates"]] == ["first", "second"]+ assert chunks[-1]["usage"] == USAGE+ msg.ack.assert_awaited_once()diff --git a/packages/sie_server/tests/processors/test_remote_chat_prompt.py b/packages/sie_server/tests/processors/test_remote_chat_prompt.pyindex 86974570d..9a905db0f 100644--- a/packages/sie_server/tests/processors/test_remote_chat_prompt.py+++ b/packages/sie_server/tests/processors/test_remote_chat_prompt.py@@ -313,3 +313,51 @@ async def test_nullable_controls_retain_default_parallel_and_legacy_output_cap(tassert len(payload["choices"][0]["message"]["tool_calls"]) == 2assert adapter.parameters["max_new_tokens"] == 64assert request["parallel_tool_calls"] is None++[email protected]("stream", [False, True])[email protected]("tools", [False, True])[email protected]("include_reasoning", [False, True])+async def test_rendered_chat_answers_reasoning_only_when_asked(+ template, stream: bool, tools: bool, include_reasoning: bool+) -> None:+ answer = '<tool_call>{"name":"lookup","arguments":{"x":1}}</tool_call>' if tools else "answer"+ adapter = RawAdapter(+ [+ GenerationChunk(text_delta="private </th"),+ GenerationChunk(text_delta="ink>" + answer),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=12, completion_tokens=3),+ ]+ )+ request = body(stream=stream)+ if tools:+ request["tools"] = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}]++ events = await remote_chat_prompt.prepare_rendered_chat(+ adapter,+ request,+ config=model(),+ requested_model="local/model",+ max_response_bytes=1024,+ include_reasoning=include_reasoning,+ )++ assert events is not None+ expected = "private " if include_reasoning else None+ if stream:+ deltas = [event["choices"][0]["delta"] async for event in events]+ reasoning = "".join(delta.get("reasoning_content", "") for delta in deltas)+ assert (reasoning or None) == expected+ first_reasoning = next((i for i, delta in enumerate(deltas) if delta.get("reasoning_content")), None)+ first_answer = next(i for i, delta in enumerate(deltas) if delta.get("content") or delta.get("tool_calls"))+ assert first_reasoning is None or first_reasoning <= first_answer+ assert all("think" not in json.dumps(delta) for delta in deltas)+ else:+ message = (await remote_chat_prompt.collect_rendered_chat(events))["choices"][0]["message"]+ assert message.get("reasoning_content") == expected+ if tools:+ assert message["tool_calls"][0]["function"]["name"] == "lookup"+ else:+ assert message["content"] == "answer"+ assert adapter.closeddiff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.pyindex 74e8fbc66..d65acda55 100644--- a/packages/sie_server/tests/processors/test_streaming.py+++ b/packages/sie_server/tests/processors/test_streaming.py@@ -20,6 +20,7 @@ import reimport threadingimport timefrom collections.abc import AsyncIterator, Mapping+from dataclasses import replacefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock@@ -4820,3 +4821,206 @@ async def test_grammar_work_item_without_its_grammar_profile_is_rejected() -> Noregistry.get.assert_not_called()assert adapter.close_calls == 0msg.ack.assert_awaited()++[email protected]("stream", [False, True])+ "tools", [None, [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}]]+)[email protected]("include_reasoning", [False, True])+async def test_queued_chat_publishes_reasoning_only_when_asked(+ monkeypatch: pytest.MonkeyPatch, stream: bool, tools: Any, include_reasoning: bool+) -> None:+ nc = AsyncMock()+ adapter = _FakeGenAdapter(+ [+ GenerationChunk(text_delta="private reas", is_first=True),+ GenerationChunk(text_delta="oning</think>Visible answer"),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=8),+ ]+ )+ registry = _make_registry_with_chat_config(+ adapter, chat_template_kwargs={"enable_thinking": True}, hf_id="Qwen/Qwen3.5-4B", reasoning_parser="qwen3"+ )+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ monkeypatch.setattr(proc, "_render_chat_template", AsyncMock(return_value="rendered prompt<think>"))+ monkeypatch.setattr("sie_server.processors.streaming._FLUSH_INTERVAL_S", 0)+ work = _make_work_item(messages=[{"role": "user", "content": "Hello"}])+ work["generate"]["stream"] = stream+ work["generate"]["include_reasoning"] = include_reasoning+ if tools is not None:+ work["generate"]["tools"] = tools++ await proc.process(_make_msg(work), "Qwen/Qwen3.5-4B")++ decoded = _decode_chunks(nc)+ assert [chunk["seq"] for chunk in decoded] == list(range(len(decoded)))+ assert "".join(chunk.get("text_delta", "") for chunk in decoded) == "Visible answer"+ reasoning = [chunk["reasoning_delta"] for chunk in decoded if "reasoning_delta" in chunk]+ if include_reasoning:+ assert "".join(reasoning) == "private reasoning"+ first_reasoning = next(index for index, chunk in enumerate(decoded) if "reasoning_delta" in chunk)+ first_text = next(index for index, chunk in enumerate(decoded) if chunk.get("text_delta"))+ assert first_reasoning < first_text+ assert all(not chunk["text_delta"] for chunk in decoded if "reasoning_delta" in chunk)+ else:+ assert reasoning == []+ assert "private" not in str(decoded)+ assert decoded[-1]["done"] is True+ assert decoded[-1]["usage"]["completion_tokens"] == 8+++async def test_queued_chat_include_reasoning_is_silent_for_a_model_without_reasoning(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ nc = AsyncMock()+ adapter = _FakeGenAdapter(+ [+ GenerationChunk(text_delta="Plain answer", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=2),+ ]+ )+ registry = _make_registry_with_chat_config(adapter, chat_template_kwargs={})+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ work = _make_work_item()+ work["generate"]["include_reasoning"] = True++ await proc.process(_make_msg(work), "test/model")++ decoded = _decode_chunks(nc)+ assert "".join(chunk.get("text_delta", "") for chunk in decoded) == "Plain answer"+ assert not any("reasoning_delta" in chunk for chunk in decoded)+ assert decoded[-1]["finish_reason"] == "stop"+++async def test_queued_chat_rejects_a_non_boolean_include_reasoning() -> None:+ nc = AsyncMock()+ adapter = _FakeGenAdapter([])+ proc = StreamingProcessor(nc=nc, registry=_make_registry_with_chat_config(adapter), worker_id="w1")+ work = _make_work_item()+ work["generate"]["include_reasoning"] = "yes"++ await proc.process(_make_msg(work), "test/model")++ terminal = _terminal_chunk(nc)+ assert terminal["error"]["code"] == "invalid_request"+ assert "include_reasoning" in terminal["error"]["message"]+ assert adapter.close_calls == 0+++def _reasoning_processor(+ monkeypatch: pytest.MonkeyPatch, script: list[GenerationChunk], *, prompt: str = "rendered prompt<think>"+) -> tuple[AsyncMock, StreamingProcessor]:+ nc = AsyncMock()+ registry = _make_registry_with_chat_config(+ _FakeGenAdapter(script),+ chat_template_kwargs={"enable_thinking": True},+ hf_id="Qwen/Qwen3.5-4B",+ reasoning_parser="qwen3",+ )+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ monkeypatch.setattr(proc, "_render_chat_template", AsyncMock(return_value=prompt))+ monkeypatch.setattr("sie_server.processors.streaming._FLUSH_INTERVAL_S", 0)+ return nc, proc+++def _reasoning_work(**generate: Any) -> dict[str, Any]:+ work = _make_work_item(messages=[{"role": "user", "content": "Hello"}])+ work["generate"].update(include_reasoning=True, **generate)+ return work++[email protected]("stream", [False, True])+async def test_queued_chat_include_reasoning_keeps_each_candidate_reasoning_on_its_choice(+ monkeypatch: pytest.MonkeyPatch, stream: bool+) -> None:+ terminal = GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=8)+ if stream:+ script = [+ GenerationChunk(text_delta="r0</think>a0", choice_index=0, is_first=True),+ GenerationChunk(text_delta="r1</think>a1", choice_index=1),+ terminal,+ ]+ else:+ script = [+ replace(+ terminal,+ candidates=(+ {"text": "r0</think>a0", "finish_reason": "stop", "logprobs": None},+ {"text": "r1</think>a1", "finish_reason": "stop", "logprobs": None},+ ),+ )+ ]+ nc, proc = _reasoning_processor(monkeypatch, script)++ await proc.process(_make_msg(_reasoning_work(n=2, stream=stream)), "Qwen/Qwen3.5-4B")++ decoded = _decode_chunks(nc)+ assert decoded[-1]["done"] is True+ if stream:+ per_choice: dict[int, dict[str, str]] = {}+ for chunk in decoded[:-1]:+ fields = per_choice.setdefault(chunk.get("choice_index", 0), {"reasoning": "", "text": ""})+ fields["reasoning"] += chunk.get("reasoning_delta", "")+ fields["text"] += chunk.get("text_delta", "")+ assert per_choice == {0: {"reasoning": "r0", "text": "a0"}, 1: {"reasoning": "r1", "text": "a1"}}+ else:+ assert not any("reasoning_delta" in chunk for chunk in decoded)+ assert [(item["text"], item["reasoning_content"]) for item in decoded[-1]["candidates"]] == [+ ("a0", "r0"),+ ("a1", "r1"),+ ]+++async def test_queued_chat_include_reasoning_publishes_text_and_reasoning_in_model_order(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ nc, proc = _reasoning_processor(+ monkeypatch,+ [+ GenerationChunk(text_delta="Hello <think>x</think> world", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=8),+ ],+ prompt="rendered prompt",+ )++ await proc.process(_make_msg(_reasoning_work(stream=True)), "Qwen/Qwen3.5-4B")++ decoded = _decode_chunks(nc)+ published = [+ (field, chunk[key])+ for chunk in decoded+ for field, key in (("reasoning", "reasoning_delta"), ("text", "text_delta"))+ if chunk.get(key)+ ]+ assert published == [("text", "Hello "), ("reasoning", "x"), ("text", " world")]+ assert [chunk["seq"] for chunk in decoded] == list(range(len(decoded)))+++async def test_queued_chat_include_reasoning_still_fails_an_answer_that_is_only_reasoning(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ nc, proc = _reasoning_processor(+ monkeypatch,+ [+ GenerationChunk(text_delta="thinking until the budget ends", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="length", prompt_tokens=1, completion_tokens=8),+ ],+ )++ await proc.process(_make_msg(_reasoning_work(stream=True)), "Qwen/Qwen3.5-4B")++ decoded = _decode_chunks(nc)+ assert "".join(chunk.get("reasoning_delta", "") for chunk in decoded) == "thinking until the budget ends"+ assert not any(chunk.get("text_delta") for chunk in decoded)+ assert decoded[-1]["done"] is True+ assert decoded[-1]["error"]["code"] == "empty_model_output"diff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.pyindex 572b7a612..50e7ede39 100644--- a/packages/sie_server/tests/processors/test_tool_call_parser.py+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py@@ -988,3 +988,27 @@ async def test_non_streaming_candidates_keep_a_malformed_block_as_text() -> None(parsed,) = out[-1].candidatesassert json.loads(parsed["tool_calls"][0]["function"]["arguments"]) == {"old_str": " a"}assert parsed["finish_reason"] == "tool_calls"+++async def test_parse_tool_call_stream_keeps_reasoning_ahead_of_the_text_it_rode_on() -> None:+ out = [+ item+ async for item in parse_tool_call_stream(+ _chunks(+ [+ GenerationChunk(text_delta="", reasoning_delta="think "),+ GenerationChunk(+ text_delta='<tool_call>{"name":"get_weather","arguments":{"city":"Paris"}}</tool_call>',+ reasoning_delta="more",+ ),+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),+ ]+ )+ )+ ]++ assert [item.reasoning_delta for item in out if item.reasoning_delta] == ["think ", "more"]+ first_tool = next(index for index, item in enumerate(out) if item.tool_call_delta is not None)+ assert all(not item.reasoning_delta for item in out[first_tool:])+ assert out[-1].finish_reason == "tool_calls"diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex f0f2db1fb..da06cda9c 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -1263,6 +1263,11 @@ export interface ChatMessage {tool_call_id?: string;/** Populated by the model when calling tools (assistant turns only). */tool_calls?: ToolCall[];+ /**+ * The model's reasoning on a response message. Present only when the+ * request set `include_reasoning` and the model produced any.+ */+ reasoning_content?: string;}/**@@ -1367,6 +1372,13 @@ export interface ChatCompletionRequest {* still applies. Absent, the serving profile decides (default on).*/schema_in_prompt?: boolean;+ /**+ * SIE extension. `true` makes the model's reasoning public as+ * `reasoning_content` on the message and, when streaming, on each delta.+ * A model whose configuration declares no reasoning answers the field with+ * nothing. Absent or `false` keeps reasoning private; `usage` is unchanged.+ */+ include_reasoning?: boolean;/** Accepted in the OpenAI range [-2, 2]; out-of-range values are rejected. */frequency_penalty?: number;presence_penalty?: number;@@ -1480,6 +1492,8 @@ export interface ChatDelta {role?: "assistant";content?: string;tool_calls?: ToolCallDelta[];+ /** Reasoning delta, present only when the request set `include_reasoning`. */+ reasoning_content?: string;}/** Partial tool-call materialised across multiple streaming chunks. */diff --git a/packages/sie_ts_sdk/tests/chat.test.ts b/packages/sie_ts_sdk/tests/chat.test.tsindex 8af734b73..dbeacf490 100644--- a/packages/sie_ts_sdk/tests/chat.test.ts+++ b/packages/sie_ts_sdk/tests/chat.test.ts@@ -372,4 +372,31 @@ describe("SIEClient.chatCompletions", () => {// stream must be forced false on the non-streaming method.expect(body.stream).toBe(false);});++ it("forwards include_reasoning and surfaces reasoning_content on the message", async () => {+ const completion: ChatCompletion = {+ ...SAMPLE_COMPLETION,+ choices: [+ {+ index: 0,+ message: { role: "assistant", content: "Hi there!", reasoning_content: "why" },+ finish_reason: "stop",+ logprobs: null,+ },+ ],+ };+ mockFetch.mockResolvedValueOnce(jsonResponse(completion));++ const client = new SIEClient("http://localhost:8080");+ const result = await client.chatCompletions({+ model: "m",+ messages: [{ role: "user", content: "hi" }],+ include_reasoning: true,+ });++ const body = JSON.parse(mockFetch.mock.calls[0][1].body);+ expect(body.include_reasoning).toBe(true);+ expect(result.choices[0]?.message.reasoning_content).toBe("why");+ expect(result.choices[0]?.message.content).toBe("Hi there!");+ });});diff --git a/packages/sie_ts_sdk/tests/sdkRequests.test.ts b/packages/sie_ts_sdk/tests/sdkRequests.test.tsindex 2ec089805..9aa1f4fa0 100644--- a/packages/sie_ts_sdk/tests/sdkRequests.test.ts+++ b/packages/sie_ts_sdk/tests/sdkRequests.test.ts@@ -201,6 +201,7 @@ const CALLS: Record<string, (client: SIEClient) => Promise<unknown>> = {messages: [{ role: "user", content: "Count to ten." }],max_completion_tokens: 64,stream_options: { include_usage: true },+ include_reasoning: true,}),),};diff --git a/packages/sie_ts_sdk/tests/streaming.test.ts b/packages/sie_ts_sdk/tests/streaming.test.tsindex 5e459efee..3b30ef899 100644--- a/packages/sie_ts_sdk/tests/streaming.test.ts+++ b/packages/sie_ts_sdk/tests/streaming.test.ts@@ -421,6 +421,42 @@ describe("SIEClient.streamChatCompletions", () => {expect(calls?.[0]?.function?.arguments).toBe('{"city":');});+ it("forwards include_reasoning and yields reasoning_content deltas unchanged", async () => {+ const reasoningChunk = JSON.stringify({+ id: "chatcmpl-x",+ object: "chat.completion.chunk",+ created: 1_700_000_000,+ model: "m",+ system_fingerprint: null,+ choices: [+ {+ index: 0,+ delta: { role: "assistant", reasoning_content: "why " },+ finish_reason: null,+ logprobs: null,+ },+ ],+ } satisfies ChatCompletionChunk);++ mockFetch.mockResolvedValueOnce(sseResponse([reasoningChunk, chatChunk("Hi")]));++ const client = new SIEClient("http://localhost:8080");+ const chunks: ChatCompletionChunk[] = [];+ for await (const chunk of client.streamChatCompletions({+ model: "m",+ messages: [{ role: "user", content: "why?" }],+ include_reasoning: true,+ })) {+ chunks.push(chunk);+ }+ expect(chunks).toHaveLength(2);+ expect(chunks[0]?.choices[0]?.delta.reasoning_content).toBe("why ");+ expect(chunks[0]?.choices[0]?.delta.content).toBeUndefined();+ expect(chunks[1]?.choices[0]?.delta.reasoning_content).toBeUndefined();+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);+ expect(body.include_reasoning).toBe(true);+ });+it("sets stream:true automatically and uses Accept: text/event-stream", async () => {mockFetch.mockResolvedValueOnce(sseResponse([chatChunk("ok")]));diff --git a/packages/sie_ts_sdk/tests/typecheck/primitive-options.ts b/packages/sie_ts_sdk/tests/typecheck/primitive-options.tsindex 9222e720a..1398d8492 100644--- a/packages/sie_ts_sdk/tests/typecheck/primitive-options.ts+++ b/packages/sie_ts_sdk/tests/typecheck/primitive-options.ts@@ -48,11 +48,12 @@ void client.extract("urchade/gliner_multi-v2.1", { text: "hello" }).then((resultreturn model;});-// The gateway's schema_in_prompt chat field is part of the request type.+// The gateway's schema_in_prompt and include_reasoning chat fields are part of the request type.const chat: ChatCompletionRequest = {model: "Qwen/Qwen3-4B-Instruct-2507",messages: [{ role: "user", content: "Extract the invoice fields." }],response_format: { type: "json_schema", json_schema: { name: "invoice", schema: {} } },schema_in_prompt: false,+ include_reasoning: true,};void client.chatCompletions(chat);diff --git a/packages/wire-fixtures/sdk_requests.json b/packages/wire-fixtures/sdk_requests.jsonindex a804466e9..081da4134 100644--- a/packages/wire-fixtures/sdk_requests.json+++ b/packages/wire-fixtures/sdk_requests.json@@ -449,7 +449,8 @@"messages": [{ "role": "user", "content": "Count to ten." }],"stream": true,"max_completion_tokens": 64,- "stream_options": { "include_usage": true }+ "stream_options": { "include_usage": true },+ "include_reasoning": true}}}