diff --git a/docs/api.md b/docs/api.md index 8eb8dbb3b..38adb8cbf 100644 --- a/docs/api.md +++ b/docs/api.md @@ -228,8 +228,9 @@ prompt and may publish prefix checkpoints for other requests. Responses and Mess ## Transport and admission Generation uses HTTP JSON or `stream: true` with SSE. WebSockets, background -execution, and hosted tools are unsupported. Anthropic requests require -`anthropic-version: 2023-06-01`. +execution, and hosted tools are unsupported; `GET /v1/responses` (including +WebSocket upgrade requests) returns HTTP 400 (`invalid_request_error`). +Anthropic requests require `anthropic-version: 2023-06-01`. When a serving key is configured, OpenAI routes use `Authorization: Bearer KEY`. Anthropic routes also accept `x-api-key: KEY`; supplying both headers requires @@ -576,7 +577,9 @@ emit a success terminator. Responses also supports text custom tools by presenti JSON `{ "input": string }` function to the model and restoring the custom call on output. Anthropic's `type: "custom"` uses its ordinary `input_schema` contract. Responses namespaces become unique `namespace__name` names in the model template -and regain their namespace on output; ambiguous names are rejected. +and regain their namespace on output; ambiguous names and duplicate namespace +declarations are rejected with HTTP 400, and empty namespace wrappers emit no +entry in `response.tools`. Responses custom tools may specify Lark or regex grammars. Helios compiles them before admission, includes their contract in the model's tool description, and @@ -741,6 +744,13 @@ lifecycle events with increasing sequence numbers. Success ends in `max_output_tokens`; generation failures end in `response.failed`. Responses SSE does not use an OpenAI Chat `[DONE]` sentinel. +Response objects in buffered responses and SSE lifecycle events echo the +request's declared `tools` and `text.format` (defaulting to `{"type":"text"}` +when `text.format` is omitted or `null`). `function_call_output` and +`custom_tool_call_output` items honor an optional boolean `is_error` flag +(defaulting to `false` when omitted or `null`), applying the same failed +tool-result lowering as Chat Completions and Messages. + Readable reasoning is returned as `reasoning_text` content with an empty summary. Opaque encrypted-only histories are rejected. Helios does not fabricate hosted provider reasoning signatures or encrypted continuation state. diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index af1728abf..5a9e3bf16 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -20,7 +20,7 @@ pub(super) async fn no_websocket() -> Response { error( Protocol::Responses, StatusCode::BAD_REQUEST, - "WebSockets are not supported; use POST /v1/responses with HTTP/SSE", + "GET /v1/responses and WebSocket transport are not supported; use POST /v1/responses with HTTP JSON or SSE", ) } fn rejection( @@ -368,6 +368,7 @@ pub(super) async fn generate( observation.include_usage, decoded.metadata, ); + encoder.set_text_format(decoded.text_format); encoder.set_logprobs( decoded.request.options.logprobs.clone(), state.frontend.clone(), @@ -701,4 +702,23 @@ mod tests { StatusCode::BAD_REQUEST ); } + + #[tokio::test] + async fn get_responses_returns_bad_request_with_http_json_and_sse_guidance() { + let response = no_websocket().await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let bytes = axum::body::to_bytes(response.into_body(), 4096).await.unwrap(); + let body: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + body, + json!({ + "error": { + "type": "invalid_request_error", + "message": "GET /v1/responses and WebSocket transport are not supported; use POST /v1/responses with HTTP JSON or SSE", + "param": null, + "code": "invalid_request_error" + } + }) + ); + } } diff --git a/helios/src/server/inference.rs b/helios/src/server/inference.rs index 39a986273..961c4eb10 100644 --- a/helios/src/server/inference.rs +++ b/helios/src/server/inference.rs @@ -58,6 +58,7 @@ pub enum Part { pub struct Tool { pub name: String, pub namespace: Option, + pub namespace_description: Option, pub description: String, pub parameters: Value, /// Whether the client declared `parameters`; `parameters` holds an empty diff --git a/helios/src/server/protocol/decode.rs b/helios/src/server/protocol/decode.rs index 425ef2513..bffd0378e 100644 --- a/helios/src/server/protocol/decode.rs +++ b/helios/src/server/protocol/decode.rs @@ -340,7 +340,7 @@ fn responses_messages(body: &Value) -> Result> { id: Some(field(&item, "call_id")?.into()), name: None, content: plain_parts(&item["output"], Protocol::Responses)?, - is_error: false, + is_error: flag(&item, "is_error", false)?, }], ), "reasoning" => { @@ -439,6 +439,7 @@ fn tool(v: &Value, protocol: Protocol, namespace: Option<&str>) -> Result Ok(Tool { name: field(definition, "name")?.into(), namespace: namespace.map(str::to_owned), + namespace_description: None, description: definition .get("description") .and_then(Value::as_str) @@ -462,7 +463,49 @@ fn thinking_budget(value: &Value) -> Result { Ok(budget) } -fn options(body: &Value, protocol: Protocol) -> Result { +fn responses_text_format(body: &Value) -> Result, Value)>> { + if !present(body, "text") { + return Ok(None); + } + let text = &body["text"]; + if !text.is_object() { + return Err("text must be a JSON object".into()); + } + if !present(text, "format") { + return Ok(None); + } + let format = &text["format"]; + if !format.is_object() { + return Err("text.format must be a JSON object".into()); + } + match field(format, "type")? { + "text" => Ok(Some((None, json!({"type": "text"})))), + "json_object" => Ok(Some(( + Some(Constraint::JsonObject), + json!({"type": "json_object"}), + ))), + "json_schema" => { + let schema = format + .get("schema") + .filter(|schema| schema.is_object() || schema.is_boolean()) + .ok_or("text.format.schema must be a JSON object or boolean")?; + let mut echoed = json!({"type": "json_schema", "schema": schema}); + if let Some(name) = optional_id(format, "name")? { + echoed["name"] = json!(name); + } + if let Some(description) = optional_id(format, "description")? { + echoed["description"] = json!(description); + } + if present(format, "strict") { + echoed["strict"] = json!(flag(format, "strict", false)?); + } + Ok(Some((Some(Constraint::Json(schema.clone())), echoed))) + } + _ => Err(unsupported("unsupported output format")), + } +} + +fn options(body: &Value, protocol: Protocol) -> Result<(Options, Option)> { let mut options = Options::default(); options.sampling = serde_json::from_value(body.clone()) .map_err(|e| format!("invalid sampling options: {e}"))?; @@ -506,28 +549,37 @@ fn options(body: &Value, protocol: Protocol) -> Result { .extend(ids.into_iter().map(|id| vec![id])); } options.ignore_eos = flag(body, "ignore_eos", false)?; - let format = match protocol { - Protocol::Responses => &body["text"]["format"], - Protocol::Messages => &body["output_config"]["format"], - _ => &body["response_format"], - }; - if !format.is_null() { - options.constraint = match field(format, "type")? { - "text" => None, - "json_object" => Some(Constraint::JsonObject), - "json_schema" => Some(Constraint::Json( - if protocol == Protocol::Chat { - &format["json_schema"]["schema"] - } else { - &format["schema"] - } - .clone(), - )), - _ => return Err(unsupported("unsupported output format")), + let (has_format, text_format) = if protocol == Protocol::Responses { + if let Some((constraint, echoed)) = responses_text_format(body)? { + options.constraint = constraint; + (true, Some(echoed)) + } else { + (false, None) + } + } else { + let format = match protocol { + Protocol::Messages => &body["output_config"]["format"], + _ => &body["response_format"], }; - } - if present(body, "grammar") { if !format.is_null() { + options.constraint = match field(format, "type")? { + "text" => None, + "json_object" => Some(Constraint::JsonObject), + "json_schema" => Some(Constraint::Json( + if protocol == Protocol::Chat { + &format["json_schema"]["schema"] + } else { + &format["schema"] + } + .clone(), + )), + _ => return Err(unsupported("unsupported output format")), + }; + } + (!format.is_null(), None) + }; + if present(body, "grammar") { + if has_format { return Err("grammar and output format are mutually exclusive".into()); } options.constraint = Some(Constraint::Lark(field(body, "grammar")?.into())); @@ -622,7 +674,7 @@ fn options(body: &Value, protocol: Protocol) -> Result { .clone(), ); } - Ok(options) + Ok((options, text_format)) } fn raw_prompts(value: &Value) -> Result> { if let Some(text) = value.as_str() { @@ -845,14 +897,21 @@ pub(crate) fn decode(protocol: Protocol, body: Value, count: bool) -> Result Result Result Frontend { let mut alphabet: Vec<_> = tokenizers::pre_tokenizers::byte_level::ByteLevel::alphabet() .into_iter() .collect(); @@ -2049,32 +2108,34 @@ mod native_prompt_tests { tokenizers::pre_tokenizers::byte_level::ByteLevel::new(false, true, false), )); tokenizer.with_decoder(Some(tokenizers::decoders::byte_level::ByteLevel::default())); + let mut markers: Vec<&str> = crate::output::tml::CONTROL_MARKERS.to_vec(); + if include_image_pad { + markers.push("<|image_pad|>"); + } tokenizer - .add_special_tokens( - crate::output::tml::CONTROL_MARKERS - .iter() - .map(|&s| AddedToken::from(s, true)), - ) + .add_special_tokens(markers.into_iter().map(|s| AddedToken::from(s, true))) .unwrap(); let eos = tokenizer .token_to_id("<|content_model_end_sampling|>") .unwrap(); - let end_message = tokenizer.token_to_id("<|end_message|>").unwrap(); - let model_tok = tokenizer.token_to_id("<|message_model|>").unwrap(); - let text_tok = tokenizer.token_to_id("<|content_text|>").unwrap(); let bytes = tokenizer.to_string(false).unwrap(); let path = std::env::temp_dir().join(format!( - "flare-tml-budget-{}-{:?}.json", + "flare-tml-fixture-{}-{:?}-{}.json", std::process::id(), - std::thread::current().id() + std::thread::current().id(), + include_image_pad )); std::fs::write(&path, &bytes).unwrap(); - let settings: FrontendSettings = serde_json::from_value(json!({ + let mut settings_json = json!({ "tokenizer": {}, "eos_token_ids": [eos], "prompt_encoder": i32::from(PromptEncoder::TmlV0), - })) - .unwrap(); + }); + if include_image_pad { + settings_json["image_placeholder_token_id"] = + json!(tokenizer.token_to_id("<|image_pad|>").unwrap()); + } + let settings: FrontendSettings = serde_json::from_value(settings_json).unwrap(); let frontend = Frontend::load_with_settings( FrontendAssets { tokenizer: Asset { @@ -2090,6 +2151,25 @@ mod native_prompt_tests { ) .unwrap(); std::fs::remove_file(path).unwrap(); + frontend + } + + #[test] + fn tml_content_headers_thinking_budget_prepares_close_and_optional_text_frame_tail() { + let frontend = tml_frontend(false); + let eos = frontend + .tokenizer() + .token_to_id("<|content_model_end_sampling|>") + .unwrap(); + let end_message = frontend.tokenizer().token_to_id("<|end_message|>").unwrap(); + let model_tok = frontend + .tokenizer() + .token_to_id("<|message_model|>") + .unwrap(); + let text_tok = frontend + .tokenizer() + .token_to_id("<|content_text|>") + .unwrap(); let mut config = crate::frontend::test_support::model_config(crate::model::testing::metadata()); config.contract.vocabulary = frontend.tokenizer().get_vocab_size(true); @@ -2192,4 +2272,132 @@ mod native_prompt_tests { assert_eq!(cut.close, vec![end_message, model_tok, text_tok]); assert_eq!(cut.after, 16); } + + #[test] + fn responses_tool_result_is_error_matches_chat_and_messages_across_prompt_encoders() { + let tml_frontend = tml_frontend(true); + let jinja_template = concat!( + "{% for m in messages %}<{{ m.role }}>", + "{% if m.content is string %}{{ m.content }}{% else %}", + "{% for block in m.content %}", + "{% if block.type == 'image_url' %}<|deepseek_image|>{% else %}{{ block.text }}{% endif %}", + "{% if not loop.last %}{{ '\\n\\n' }}{% endif %}{% endfor %}{% endif %}", + "{% mark %}{% endfor %}" + ); + let frontends = [ + ( + PromptEncoder::Jinja, + renderer(PromptEncoder::Jinja, Some(jinja_template), TemplateEncoding::Text).0, + ), + (PromptEncoder::DeepseekV4, native(PromptEncoder::DeepseekV4).0), + (PromptEncoder::DeepseekV41, native(PromptEncoder::DeepseekV41).0), + (PromptEncoder::TmlV0, tml_frontend), + ]; + let image_url = "data:image/png;base64,AA=="; + + for (encoder, frontend) in &frontends { + for multimodal in [false, true] { + for is_error in [false, true] { + let chat_content = if multimodal { + json!([ + {"type": "text", "text": "disk full"}, + {"type": "image_url", "image_url": {"url": image_url}} + ]) + } else { + json!("disk full") + }; + let msg_content = if multimodal { + json!([ + {"type": "text", "text": "disk full"}, + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AA=="}} + ]) + } else { + json!("disk full") + }; + let resp_output = if multimodal { + json!([ + {"type": "input_text", "text": "disk full"}, + {"type": "input_image", "image_url": image_url} + ]) + } else { + json!("disk full") + }; + + let render = |protocol: Protocol, body: Value| { + let decoded = decode(protocol, body, false).unwrap(); + let (normalized, _, options) = + crate::server::request::template_inputs(frontend, &decoded.request, 0) + .unwrap(); + frontend.render_chat(&normalized, &options).unwrap() + }; + + let chat = render( + Protocol::Chat, + json!({ + "messages": [ + {"role": "user", "content": "Run"}, + {"role": "assistant", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "exec", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "c1", "is_error": is_error, "content": chat_content} + ] + }), + ); + let messages = render( + Protocol::Messages, + json!({ + "max_tokens": 8, + "messages": [ + {"role": "user", "content": "Run"}, + {"role": "assistant", "content": [{"type": "tool_use", "id": "c1", "name": "exec", "input": {}}]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "c1", "is_error": is_error, "content": msg_content}]} + ] + }), + ); + + for kind in ["function_call_output", "custom_tool_call_output"] { + let responses = render( + Protocol::Responses, + json!({ + "input": [ + {"role": "user", "content": "Run"}, + {"type": "function_call", "call_id": "c1", "name": "exec", "arguments": "{}"}, + {"type": kind, "call_id": "c1", "is_error": is_error, "output": resp_output} + ] + }), + ); + assert_eq!( + responses.text, chat.text, + "{encoder:?} {kind} multimodal={multimodal} is_error={is_error}" + ); + assert_eq!(responses.token_ids, chat.token_ids); + assert_eq!(responses.image_sources, chat.image_sources); + assert_eq!(responses.text, messages.text); + assert_eq!(responses.token_ids, messages.token_ids); + assert_eq!(responses.image_sources, messages.image_sources); + + if multimodal { + assert_eq!(responses.image_sources, vec![image_url]); + } else { + assert!(responses.image_sources.is_empty()); + } + if *encoder == PromptEncoder::TmlV0 { + assert_eq!( + responses.text.contains("<|content_tool_error|>"), + is_error, + "{}", + responses.text + ); + assert!(!responses.text.contains("Tool execution failed:")); + } else { + assert_eq!( + responses.text.contains("Tool execution failed:"), + is_error, + "{encoder:?}: {}", + responses.text + ); + } + } + } + } + } + } } diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 2d1ddabcf..848f9c920 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -19,6 +19,62 @@ use sha2::{Digest, Sha256}; pub(super) fn thinking_signature(text: &str) -> String { format!("flare-thinking-v1:{:x}", Sha256::digest(text.as_bytes())) } + +fn responses_tool_entry(tool: &Tool) -> Value { + let mut entry = if tool.custom { + let format = match &tool.grammar { + Some(grammar) => json!({ + "type": "grammar", + "syntax": grammar.syntax, + "definition": grammar.source, + }), + None => json!({"type": "text"}), + }; + json!({ + "type": "custom", + "name": tool.name, + "format": format, + }) + } else { + json!({ + "type": "function", + "name": tool.name, + "parameters": if tool.declared_parameters { + tool.parameters.clone() + } else { + Value::Null + }, + "strict": tool.strict, + }) + }; + if !tool.description.is_empty() { + entry["description"] = json!(tool.description); + } + entry +} +fn build_responses_tools(tools: &[Tool]) -> Value { + let mut out: Vec = Vec::new(); + let mut namespaces: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for tool in tools { + let entry = responses_tool_entry(tool); + if let Some(ns) = tool.namespace.as_deref() { + if let Some(&index) = namespaces.get(ns) { + out[index]["tools"].as_array_mut().unwrap().push(entry); + } else { + namespaces.insert(ns, out.len()); + out.push(json!({ + "type": "namespace", + "name": ns, + "description": tool.namespace_description.as_deref().unwrap_or(""), + "tools": [entry], + })); + } + } else { + out.push(entry); + } + } + Value::Array(out) +} #[derive(Clone, Debug)] pub(crate) struct Frame { pub event: Option, @@ -97,6 +153,8 @@ pub(crate) struct Encoder { stop: Option, sequence: u64, metadata: Value, + responses_tools: Value, + text_format: Option, incomplete_item: Option, } impl Encoder { @@ -114,6 +172,11 @@ impl Encoder { metadata: Value, ) -> Self { let choices = prompts.len() * choices_per_prompt; + let responses_tools = if protocol == Protocol::Responses { + build_responses_tools(&tools) + } else { + Value::Null + }; Self { protocol, logprob_format: None, @@ -150,9 +213,14 @@ impl Encoder { stop: None, sequence: 0, metadata, + responses_tools, + text_format: None, incomplete_item: None, } } + pub fn set_text_format(&mut self, format: Option) { + self.text_format = format; + } pub fn set_tool_grammars( &mut self, grammars: std::collections::HashMap, @@ -256,8 +324,8 @@ impl Encoder { Protocol::Responses => { let response = self.response(); vec![ - self.named("response.created", json!({"response":response})), - self.named("response.in_progress", json!({"response":self.response()})), + self.named("response.created", json!({"response": response.clone()})), + self.named("response.in_progress", json!({"response": response})), ] } } @@ -753,7 +821,11 @@ impl Encoder { "name": name, }), }; - json!({"id":self.id,"object":"response","created_at":self.created,"model":self.model,"status":if !complete{"in_progress"}else if incomplete{"incomplete"}else{"completed"},"error":null,"incomplete_details":if incomplete{json!({"reason":"max_output_tokens"})}else{Value::Null},"output":(0..self.outputs[0].blocks.len()).map(|i|self.item(i,complete)).collect::>(),"usage":if complete{self.usage_value()}else{Value::Null},"store":false,"metadata":self.metadata,"parallel_tool_calls":self.parallel_tool_calls,"tool_choice":tool_choice,"tools":[],"text":{"format":{"type":"text"}}}) + let text_format = self + .text_format + .clone() + .unwrap_or_else(|| json!({"type": "text"})); + json!({"id":self.id,"object":"response","created_at":self.created,"model":self.model,"status":if !complete{"in_progress"}else if incomplete{"incomplete"}else{"completed"},"error":null,"incomplete_details":if incomplete{json!({"reason":"max_output_tokens"})}else{Value::Null},"output":(0..self.outputs[0].blocks.len()).map(|i|self.item(i,complete)).collect::>(),"usage":if complete{self.usage_value()}else{Value::Null},"store":false,"metadata":self.metadata,"parallel_tool_calls":self.parallel_tool_calls,"tool_choice":tool_choice,"tools":self.responses_tools,"text":{"format":text_format}}) } } } diff --git a/helios/src/server/protocol/mod.rs b/helios/src/server/protocol/mod.rs index a824116d2..c267d8b72 100644 --- a/helios/src/server/protocol/mod.rs +++ b/helios/src/server/protocol/mod.rs @@ -64,6 +64,7 @@ pub(super) struct Decoded { pub echo: bool, pub observation: ObservationOptions, pub metadata: Value, + pub text_format: Option, } #[cfg(test)] diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index b2204d552..e8159a1d8 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -18,6 +18,7 @@ fn tools() -> Vec { vec![inference::Tool { name: "lookup".into(), namespace: None, + namespace_description: None, description: "Find a value".into(), parameters: json!({"type":"object"}), declared_parameters: true, @@ -1850,6 +1851,7 @@ fn strict_function_tools_decode_and_gate_streaming_and_buffered_output_across_pr let strict_tools = vec![inference::Tool { name: "lookup".into(), namespace: None, + namespace_description: None, description: String::new(), parameters: schema.clone(), declared_parameters: true, @@ -2215,6 +2217,7 @@ fn strict_tool_wires_reach_encoder_only_after_parser_completion() { let strict_tools = vec![inference::Tool { name: "lookup".into(), namespace: None, + namespace_description: None, description: String::new(), parameters: schema.clone(), declared_parameters: true, @@ -2563,6 +2566,7 @@ fn unclosed_tagged_tool_calls_at_eos_match_protocol_and_control_semantics() { vec![inference::Tool { name: "lookup".into(), namespace: None, + namespace_description: None, description: String::new(), parameters: json!({"type":"object","properties":{"query":{"type":"string"}}}), declared_parameters: true, @@ -2892,6 +2896,7 @@ fn synthesized_tool_call_ids_stay_bounded_across_protocols_modes_and_restarts() let strict_tools = vec![inference::Tool { name: "lookup".into(), namespace: None, + namespace_description: None, description: String::new(), parameters: schema.clone(), declared_parameters: true, @@ -3116,3 +3121,687 @@ fn synthesized_high_counter_tool_call_ids_round_trip_through_decode_and_template assert_eq!(rendered[3]["content"], "second_result"); } } + +#[test] +fn responses_tools_echo_and_round_trip_standalone_custom_and_namespaces() { + let schema = json!({ + "type": "object", + "properties": {"q": {"type": "string"}}, + "required": ["q"], + "additionalProperties": false + }); + let declared_tools = json!([ + { + "type": "function", + "name": "search", + "description": "Search docs", + "parameters": schema, + "strict": true + }, + { + "type": "function", + "name": "ping" + }, + { + "type": "custom", + "name": "notes", + "description": "Freeform note" + }, + { + "type": "custom", + "name": "patch", + "description": "Apply patch", + "format": {"type": "grammar", "syntax": "lark", "definition": "start: /ok/"} + }, + { + "type": "namespace", + "name": "db", + "description": "Database helpers", + "tools": [ + { + "type": "function", + "name": "query", + "description": "Run SQL", + "parameters": {"type": "object", "properties": {"sql": {"type": "string"}}}, + "strict": false + }, + { + "type": "custom", + "name": "raw", + "description": "Raw SQL" + }, + { + "type": "custom", + "name": "regex_sql", + "description": "Matched SQL", + "format": {"type": "grammar", "syntax": "regex", "definition": "SELECT [a-z]+"} + } + ] + }, + { + "type": "namespace", + "name": "empty_desc", + "description": "", + "tools": [ + {"type": "function", "name": "noop", "description": "No-op"} + ] + }, + { + "type": "namespace", + "name": "omitted_desc", + "tools": [ + {"type": "function", "name": "stat", "description": "Stat"} + ] + } + ]); + let expected_echoed = json!([ + { + "type": "function", + "name": "search", + "description": "Search docs", + "parameters": schema, + "strict": true + }, + { + "type": "function", + "name": "ping", + "parameters": null, + "strict": false + }, + { + "type": "custom", + "name": "notes", + "description": "Freeform note", + "format": {"type": "text"} + }, + { + "type": "custom", + "name": "patch", + "description": "Apply patch", + "format": {"type": "grammar", "syntax": "lark", "definition": "start: /ok/"} + }, + { + "type": "namespace", + "name": "db", + "description": "Database helpers", + "tools": [ + { + "type": "function", + "name": "query", + "description": "Run SQL", + "parameters": {"type": "object", "properties": {"sql": {"type": "string"}}}, + "strict": false + }, + { + "type": "custom", + "name": "raw", + "description": "Raw SQL", + "format": {"type": "text"} + }, + { + "type": "custom", + "name": "regex_sql", + "description": "Matched SQL", + "format": {"type": "grammar", "syntax": "regex", "definition": "SELECT [a-z]+"} + } + ] + }, + { + "type": "namespace", + "name": "empty_desc", + "description": "", + "tools": [ + {"type": "function", "name": "noop", "description": "No-op", "parameters": null, "strict": false} + ] + }, + { + "type": "namespace", + "name": "omitted_desc", + "description": "", + "tools": [ + {"type": "function", "name": "stat", "description": "Stat", "parameters": null, "strict": false} + ] + } + ]); + + for (choice, expected_choice) in [ + (json!("auto"), json!("auto")), + (json!("none"), json!("none")), + (json!("required"), json!("required")), + ( + json!({"type": "function", "name": "search"}), + json!({"type": "function", "name": "search"}), + ), + ( + json!({"type": "custom", "name": "patch"}), + json!({"type": "custom", "name": "patch"}), + ), + ( + json!({"type": "function", "name": "db__query"}), + json!({"type": "function", "name": "db__query"}), + ), + ] { + let decoded = decode( + Protocol::Responses, + json!({"input": "Hello", "tools": declared_tools, "tool_choice": choice}), + false, + ) + .unwrap(); + let mut enc = Encoder::new( + Protocol::Responses, + "resp_rt".into(), + "model".into(), + 1, + 1, + vec![PromptUsage { + tokens: 5, + image_tokens: 0, + }], + decoded.request.tools.clone(), + decoded.request.tool_choice.clone(), + decoded.request.parallel_tool_calls, + false, + json!({}), + ); + let started = enc.start(); + assert_eq!(started[0].data["response"]["tools"], expected_echoed); + assert_eq!(started[1].data["response"]["tools"], expected_echoed); + assert_eq!(enc.response()["tools"], expected_echoed); + assert_eq!(enc.response()["tool_choice"], expected_choice); + + // Round-trip: decode(encode(decode(x))) == decode(x) + let round_tripped = decode( + Protocol::Responses, + json!({ + "input": "Hello", + "tools": enc.response()["tools"], + "tool_choice": enc.response()["tool_choice"] + }), + false, + ) + .unwrap(); + assert_eq!(round_tripped.request, decoded.request); + } + + // Verify template_inputs preserves namespace description ordering before grammar instructions + // and adds no spurious leading newline for omitted or empty namespace descriptions. + let decoded = decode( + Protocol::Responses, + json!({"input": "Hello", "tools": declared_tools}), + false, + ) + .unwrap(); + let round_tripped = { + let enc = Encoder::new( + Protocol::Responses, + "resp_tpl".into(), + "model".into(), + 1, + 1, + vec![PromptUsage::default()], + decoded.request.tools.clone(), + ToolChoice::Auto, + true, + false, + json!({}), + ); + decode( + Protocol::Responses, + json!({"input": "Hello", "tools": enc.response()["tools"]}), + false, + ) + .unwrap() + }; + let frontend = { + use crate::frontend::{Asset, Frontend, FrontendAssets, FrontendSettings, TokenizerSettings}; + use sha2::{Digest, Sha256}; + let vocabulary: tokenizers::models::bpe::Vocab = [("a".into(), 0u32), ("b".into(), 1u32)] + .into_iter() + .collect(); + let mut tokenizer = tokenizers::Tokenizer::new( + tokenizers::models::bpe::BPE::builder() + .vocab_and_merges(vocabulary, vec![]) + .build() + .unwrap(), + ); + tokenizer + .add_special_tokens([tokenizers::AddedToken::from("", true)]) + .unwrap(); + let eos = tokenizer.token_to_id("").unwrap(); + let bytes = tokenizer.to_string(false).unwrap(); + let template = "{% for m in messages %}{{ m.content }}{% mark %}{% endfor %}"; + let path = std::env::temp_dir().join(format!( + "flare-protocol-tools-{}-{:?}.json", + std::process::id(), + std::thread::current().id() + )); + let template_path = path.with_extension("jinja"); + std::fs::write(&path, &bytes).unwrap(); + std::fs::write(&template_path, template).unwrap(); + let settings: FrontendSettings = + serde_json::from_value(json!({"tokenizer": {}, "eos_token_ids": [eos]})).unwrap(); + let loaded = Frontend::load_with_settings( + FrontendAssets { + tokenizer: Asset { + path: path.clone(), + range: None, + sha256: format!("{:x}", Sha256::digest(bytes.as_bytes())), + }, + tokens: TokenizerSettings::default(), + chat_template: Some(Asset { + path: template_path.clone(), + range: None, + sha256: format!("{:x}", Sha256::digest(template.as_bytes())), + }), + }, + Default::default(), + &settings, + ) + .unwrap(); + std::fs::remove_file(path).unwrap(); + std::fs::remove_file(template_path).unwrap(); + loaded + }; + let (m1, r1, o1) = + crate::server::request::template_inputs(&frontend, &decoded.request, 0).unwrap(); + let (m2, r2, o2) = + crate::server::request::template_inputs(&frontend, &round_tripped.request, 0).unwrap(); + assert_eq!((&m1, &r1, &o1), (&m2, &r2, &o2)); + let lowered_tools = o1["tools"].as_array().unwrap(); + let by_name = |name: &str| { + lowered_tools + .iter() + .find(|t| t["function"]["name"] == name) + .unwrap()["function"]["description"] + .as_str() + .unwrap() + }; + assert_eq!(by_name("db__query"), "Database helpers\nRun SQL"); + assert_eq!(by_name("db__raw"), "Database helpers\nRaw SQL"); + assert!(by_name("db__regex_sql").starts_with( + "Database helpers\nMatched SQL\nPut the complete tool input in the input string. It must match this regex grammar exactly:\nSELECT [a-z]+" + )); + assert_eq!(by_name("empty_desc__noop"), "No-op"); + assert_eq!(by_name("omitted_desc__stat"), "Stat"); + + // Empty namespace wrapper produces no callable tools and echoes []. + let empty_ns = decode( + Protocol::Responses, + json!({"input": "Hello", "tools": [{"type": "namespace", "name": "empty", "description": "Unused", "tools": []}]}), + false, + ) + .unwrap(); + assert!(empty_ns.request.tools.is_empty()); + let enc = Encoder::new( + Protocol::Responses, + "resp_empty_ns".into(), + "model".into(), + 1, + 1, + vec![PromptUsage::default()], + empty_ns.request.tools, + ToolChoice::Auto, + true, + false, + json!({}), + ); + assert_eq!(enc.response()["tools"], json!([])); + + // Duplicate namespace names in one request are rejected. + for dup_tools in [ + json!([ + {"type": "namespace", "name": "db", "description": "First", "tools": [{"type": "function", "name": "a"}]}, + {"type": "namespace", "name": "db", "description": "Second", "tools": [{"type": "function", "name": "b"}]} + ]), + json!([ + {"type": "namespace", "name": "db", "tools": []}, + {"type": "namespace", "name": "db", "tools": [{"type": "function", "name": "a"}]} + ]), + ] { + let err = decode( + Protocol::Responses, + json!({"input": "Hello", "tools": dup_tools}), + false, + ) + .err() + .unwrap(); + assert!( + err.to_string().contains("duplicate tool namespace"), + "{err}" + ); + } +} + +#[test] +fn responses_text_format_validation_echo_and_grammar_exclusion() { + use crate::server::inference::Constraint; + + // Default when text or text.format is omitted or null: Decoded leaves text_format as None + // and Encoder materializes {"type": "text"}. Explicit {"type": "text"} is preserved as Some. + for (body, expected_decoded) in [ + (json!({"input": "Hello"}), None), + (json!({"input": "Hello", "text": null}), None), + (json!({"input": "Hello", "text": {}}), None), + (json!({"input": "Hello", "text": {"format": null}}), None), + ( + json!({"input": "Hello", "text": {"format": {"type": "text"}}}), + Some(json!({"type": "text"})), + ), + ] { + let decoded = decode(Protocol::Responses, body, false).unwrap(); + assert_eq!(decoded.text_format, expected_decoded); + assert_eq!(decoded.request.options.constraint, None); + let mut enc = encoder(Protocol::Responses); + enc.set_text_format(decoded.text_format); + assert_eq!(enc.response()["text"]["format"], json!({"type": "text"})); + } + + // json_object echoes {"type": "json_object"} and sets Constraint::JsonObject. + let json_obj = decode( + Protocol::Responses, + json!({"input": "Hello", "text": {"format": {"type": "json_object"}}}), + false, + ) + .unwrap(); + assert_eq!(json_obj.text_format, Some(json!({"type": "json_object"}))); + assert_eq!(json_obj.request.options.constraint, Some(Constraint::JsonObject)); + + // json_schema echoes validated schema + optional metadata, omitting null/absent/extra fields. + let schema = json!({"type": "object", "properties": {"ok": {"type": "boolean"}}}); + let full = decode( + Protocol::Responses, + json!({ + "input": "Hello", + "text": { + "format": { + "type": "json_schema", + "name": "reply", + "description": "Reply payload", + "strict": true, + "schema": schema, + "extra_ignored": 42 + } + } + }), + false, + ) + .unwrap(); + let expected_full = json!({ + "type": "json_schema", + "name": "reply", + "description": "Reply payload", + "strict": true, + "schema": schema + }); + assert_eq!(full.text_format, Some(expected_full.clone())); + assert_eq!( + full.request.options.constraint, + Some(Constraint::Json(schema.clone())) + ); + + let minimal_and_nulls = decode( + Protocol::Responses, + json!({ + "input": "Hello", + "text": { + "format": { + "type": "json_schema", + "name": null, + "description": null, + "strict": null, + "schema": schema + } + } + }), + false, + ) + .unwrap(); + assert_eq!( + minimal_and_nulls.text_format, + Some(json!({"type": "json_schema", "schema": schema})) + ); + + // Boolean schemas match helios/src/grammar.rs and preserve strict: false. + for bool_schema in [true, false] { + let decoded = decode( + Protocol::Responses, + json!({ + "input": "Hello", + "text": {"format": {"type": "json_schema", "schema": bool_schema, "strict": false}} + }), + false, + ) + .unwrap(); + assert_eq!( + decoded.text_format, + Some(json!({"type": "json_schema", "schema": bool_schema, "strict": false})) + ); + assert_eq!( + decoded.request.options.constraint, + Some(Constraint::Json(json!(bool_schema))) + ); + } + + // Encoder echoes configured text_format in response() and all SSE lifecycle events. + let mut enc = encoder(Protocol::Responses); + enc.set_text_format(full.text_format.clone()); + let started = enc.start(); + assert_eq!(started[0].data["response"]["text"]["format"], expected_full); + assert_eq!(started[1].data["response"]["text"]["format"], expected_full); + assert_eq!(enc.response()["text"]["format"], expected_full); + let failed = enc.failure(&"boom".into()); + assert_eq!(failed.data["response"]["text"]["format"], expected_full); + + // Invalid text and text.format shapes are rejected with clear errors. + for (body, expected_error) in [ + (json!({"input": "x", "text": "bad"}), "text must be a JSON object"), + (json!({"input": "x", "text": 1}), "text must be a JSON object"), + (json!({"input": "x", "text": []}), "text must be a JSON object"), + (json!({"input": "x", "text": {"format": "text"}}), "text.format must be a JSON object"), + (json!({"input": "x", "text": {"format": []}}), "text.format must be a JSON object"), + (json!({"input": "x", "text": {"format": {"type": "xml"}}}), "unsupported output format"), + ( + json!({"input": "x", "text": {"format": {"type": "json_schema"}}}), + "text.format.schema must be a JSON object or boolean", + ), + ( + json!({"input": "x", "text": {"format": {"type": "json_schema", "schema": null}}}), + "text.format.schema must be a JSON object or boolean", + ), + ( + json!({"input": "x", "text": {"format": {"type": "json_schema", "schema": 7}}}), + "text.format.schema must be a JSON object or boolean", + ), + ( + json!({"input": "x", "text": {"format": {"type": "json_schema", "schema": "obj"}}}), + "text.format.schema must be a JSON object or boolean", + ), + ( + json!({"input": "x", "text": {"format": {"type": "json_schema", "schema": []}}}), + "text.format.schema must be a JSON object or boolean", + ), + ( + json!({"input": "x", "text": {"format": {"type": "json_schema", "schema": {}, "name": 3}}}), + "name must be a string", + ), + ( + json!({"input": "x", "text": {"format": {"type": "json_schema", "schema": {}, "description": true}}}), + "description must be a string", + ), + ( + json!({"input": "x", "text": {"format": {"type": "json_schema", "schema": {}, "strict": "true"}}}), + "strict must be boolean", + ), + ] { + let err = decode(Protocol::Responses, body.clone(), false).err().unwrap(); + assert!( + err.to_string().contains(expected_error), + "body={body} err={err}" + ); + } + + // grammar succeeds with omitted/null text.format (echoing {"type": "text"}) and rejects explicit text.format. + for body in [ + json!({"input": "x", "grammar": "start: /ok/"}), + json!({"input": "x", "grammar": "start: /ok/", "text": null}), + json!({"input": "x", "grammar": "start: /ok/", "text": {}}), + json!({"input": "x", "grammar": "start: /ok/", "text": {"format": null}}), + ] { + let decoded = decode(Protocol::Responses, body, false).unwrap(); + assert_eq!(decoded.text_format, None); + assert_eq!( + decoded.request.options.constraint, + Some(Constraint::Lark("start: /ok/".into())) + ); + } + for format in [ + json!({"type": "text"}), + json!({"type": "json_object"}), + json!({"type": "json_schema", "schema": {"type": "object"}}), + ] { + let err = decode( + Protocol::Responses, + json!({"input": "x", "grammar": "start: /ok/", "text": {"format": format}}), + false, + ) + .err() + .unwrap(); + assert!( + err.to_string().contains("mutually exclusive"), + "{err}" + ); + } +} + +#[test] +fn responses_tool_outputs_decode_is_error_and_match_chat_and_messages() { + let image_url = "data:image/png;base64,AA=="; + for kind in ["function_call_output", "custom_tool_call_output"] { + // Explicit true, false, null, and omitted. + for (flag_value, expected) in [ + (Some(json!(true)), true), + (Some(json!(false)), false), + (Some(Value::Null), false), + (None, false), + ] { + let mut item = json!({ + "type": kind, + "call_id": "call_1", + "output": [ + {"type": "input_text", "text": "timeout"}, + {"type": "input_image", "image_url": image_url} + ] + }); + if let Some(value) = flag_value { + item["is_error"] = value; + } + let decoded = decode( + Protocol::Responses, + json!({ + "input": [ + {"role": "user", "content": "Go"}, + {"type": "function_call", "call_id": "call_1", "name": "lookup", "arguments": "{}"}, + item + ] + }), + false, + ) + .unwrap(); + let Input::Conversation(messages) = &decoded.request.input else { + panic!() + }; + assert_eq!( + messages[2].parts, + vec![Part::ToolResult { + id: Some("call_1".into()), + name: None, + content: vec![ + Part::Text("timeout".into()), + Part::Image(image_url.into()), + ], + is_error: expected, + }] + ); + + // Parity with Chat Completions and Anthropic Messages. + let chat = request( + Protocol::Chat, + json!({ + "messages": [ + {"role": "user", "content": "Go"}, + {"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}}]}, + { + "role": "tool", + "tool_call_id": "call_1", + "is_error": expected, + "content": [ + {"type": "text", "text": "timeout"}, + {"type": "image_url", "image_url": {"url": image_url}} + ] + } + ] + }), + ); + let anthropic = request( + Protocol::Messages, + json!({ + "max_tokens": 8, + "messages": [ + {"role": "user", "content": "Go"}, + {"role": "assistant", "content": [{"type": "tool_use", "id": "call_1", "name": "lookup", "input": "{}"}]}, + { + "role": "user", + "content": [{ + "type": "tool_result", + "tool_use_id": "call_1", + "is_error": expected, + "content": [ + {"type": "text", "text": "timeout"}, + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AA=="}} + ] + }] + } + ] + }), + ); + let Input::Conversation(chat_msgs) = &chat.input else { panic!() }; + let Input::Conversation(anth_msgs) = &anthropic.input else { panic!() }; + for failure_text in [false, true] { + let resp_lowered = + template_messages(messages, ToolChoice::Auto, &[], failure_text).unwrap(); + let chat_lowered = + template_messages(chat_msgs, ToolChoice::Auto, &[], failure_text).unwrap(); + let anth_lowered = + template_messages(anth_msgs, ToolChoice::Auto, &[], failure_text).unwrap(); + assert_eq!(resp_lowered, chat_lowered, "{kind} failure_text={failure_text}"); + assert_eq!(resp_lowered, anth_lowered, "{kind} failure_text={failure_text}"); + assert_eq!(resp_lowered[2]["is_error"], expected); + if expected && failure_text { + assert_eq!(resp_lowered[2]["content"][0]["text"], "Tool execution failed:"); + assert_eq!(resp_lowered[2]["content"][1]["text"], "timeout"); + assert_eq!(resp_lowered[2]["content"][2]["image_url"]["url"], image_url); + } else { + assert_eq!(resp_lowered[2]["content"][0]["text"], "timeout"); + assert_eq!(resp_lowered[2]["content"][1]["image_url"]["url"], image_url); + } + } + } + + // Non-boolean is_error is rejected. + for bad in [json!("true"), json!(1), json!([]), json!({})] { + let err = decode( + Protocol::Responses, + json!({ + "input": [{"type": kind, "call_id": "call_1", "output": "err", "is_error": bad}] + }), + false, + ) + .err() + .unwrap(); + assert!( + err.to_string().contains("is_error must be boolean"), + "{kind} {bad}: {err}" + ); + } + } +} diff --git a/helios/src/server/request.rs b/helios/src/server/request.rs index ecd37897a..399e9fe3e 100644 --- a/helios/src/server/request.rs +++ b/helios/src/server/request.rs @@ -537,9 +537,19 @@ pub(super) fn template_inputs<'a>( _ => true, } }).map(|tool| { + let base = match tool + .namespace_description + .as_deref() + .filter(|s| !s.is_empty()) + { + Some(prefix) => format!("{prefix}\n{}", tool.description), + None => tool.description.clone(), + }; let description = if let Some(grammar) = &tool.grammar { - format!("{}\nPut the complete tool input in the input string. It must match this {} grammar exactly:\n{}", tool.description, grammar.syntax, grammar.source) - } else { tool.description.clone() }; + format!("{base}\nPut the complete tool input in the input string. It must match this {} grammar exactly:\n{}", grammar.syntax, grammar.source) + } else { + base + }; let mut function = serde_json::json!({"name":tool.native_name(), "description":description, "parameters":tool.parameters}); // TMLv0 distinguishes absent parameters from an empty object schema. if !tool.declared_parameters && frontend.prompt_encoder() == crate::frontend::PromptEncoder::TmlV0 { @@ -755,6 +765,7 @@ mod tests { let tool = |name: &str, parameters: Value| Tool { name: name.into(), namespace: None, + namespace_description: None, description: String::new(), parameters, declared_parameters: true, diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 6ca976e5d..e3ec16280 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -4699,6 +4699,248 @@ async fn disabled_parallel_calls_complete_http_and_stop_decoding() { } } +#[tokio::test] +async fn responses_http_generate_echoes_tools_and_text_format_across_lifecycle() { + use axum::{Extension, extract::State}; + use serde_json::{Value, json}; + + let json_schema_format = json!({ + "type": "json_schema", + "name": "answer", + "description": "Structured answer", + "strict": true, + "schema": { + "type": "object", + "properties": {"a": {"type": "integer"}}, + "required": ["a"], + "additionalProperties": false + } + }); + let declared_tools = json!([ + { + "type": "function", + "name": "lookup", + "description": "Find record", + "parameters": {"type": "object", "properties": {"a": {"type": "string"}}}, + "strict": false + }, + { + "type": "custom", + "name": "note", + "description": "Write note", + "format": {"type": "text"} + }, + { + "type": "namespace", + "name": "db", + "description": "DB tools", + "tools": [ + {"type": "function", "name": "get", "parameters": null, "strict": false} + ] + } + ]); + let make_state = || { + use crate::model::contract::{ToolParser, ToolParserKind}; + let mut fixture = Fixture::with_template( + b"a{% mark %}a", + &[""], + &["{", "}", "\"", ":", "1"], + ); + fixture.config.contract.frontend.tools = Some(ToolParser { + kind: ToolParserKind::QwenCoder, + wrapping_newlines: 0, + tag_separator: String::new(), + }); + for graph in &mut fixture.config.contract.graphs { + graph.inputs.retain(|binding| { + !matches!( + binding.source, + crate::model::contract::ValueSource::ImageFeatureIndex + | crate::model::contract::ValueSource::ImageFeatureSlot + ) + }); + } + let (sender, receiver) = mpsc::sync_channel(4); + let state = http_state_for(fixture, sender, None, &[]); + (state, receiver) + }; + let send = |state: Arc, body: Value| async move { + let ingress = Arc::new(state.ingress_slots.clone().acquire_owned().await.unwrap()); + let request = axum::http::Request::builder() + .method("POST") + .uri("/v1/responses") + .header("content-type", "application/json") + .body(axum::body::Body::from(body.to_string())) + .unwrap(); + super::super::http::generate(State(state), Extension(ingress), request).await + }; + + // Invalid text.format returns HTTP 400 without admitting work to the model queue. + { + let (state, receiver) = make_state(); + let response = send( + state, + json!({ + "input": "a", + "tools": declared_tools, + "text": {"format": {"type": "json_schema", "schema": 123}} + }), + ) + .await; + assert_eq!(response.status(), axum::http::StatusCode::BAD_REQUEST); + let bytes = axum::body::to_bytes(response.into_body(), 16384).await.unwrap(); + let body: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["error"]["type"], "invalid_request_error"); + assert!(receiver.try_recv().is_err()); + } + + // Completed (json_object and json_schema), incomplete (max_output_tokens), and failed (unsatisfied required tool_choice). + for (label, text_format, tool_choice, termination, expected_terminal_event) in [ + ( + "completed_json_object", + json!({"type": "json_object"}), + json!("auto"), + crate::output::Termination::Eos, + "response.completed", + ), + ( + "completed_json_schema", + json_schema_format.clone(), + json!("auto"), + crate::output::Termination::Eos, + "response.completed", + ), + ( + "incomplete_json_schema", + json_schema_format.clone(), + json!("auto"), + crate::output::Termination::OutputLimit, + "response.incomplete", + ), + ( + "failed_required_tool_choice", + json!({"type": "json_object"}), + json!("required"), + crate::output::Termination::Eos, + "response.failed", + ), + ] { + for stream in [false, true] { + let (state, receiver) = make_state(); + let open_tok = state.frontend.tokenizer().token_to_id("{").unwrap(); + let full_tokens: Vec = ["{", "\"", "a", "\"", ":", "1", "}"] + .into_iter() + .map(|text| state.frontend.tokenizer().token_to_id(text).unwrap()) + .collect(); + let body = json!({ + "input": "a", + "stream": stream, + "max_output_tokens": if termination == crate::output::Termination::OutputLimit { 1 } else { 16 }, + "tools": declared_tools, + "tool_choice": tool_choice, + "text": {"format": text_format} + }); + let handle = tokio::spawn(send(state, body)); + let incoming = match tokio::task::spawn_blocking(move || { + receiver.recv_timeout(std::time::Duration::from_secs(5)) + }) + .await + .unwrap() + { + Ok(incoming) => incoming, + Err(err) => { + let response = handle.await.unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 16384) + .await + .unwrap(); + panic!( + "{label} stream={stream}: queue recv failed ({err}): status={status} body={}", + String::from_utf8_lossy(&bytes) + ); + } + }; + incoming[0].notify_admission(Ok(())); + if termination == crate::output::Termination::OutputLimit { + incoming[0].emit_token(open_tok); + incoming[0].emit(GenerationEvent::Finished { + prompt_tokens: incoming[0].prompt.tokens.len(), + generated_tokens: 1, + reused_prompt_tokens: 0, + reason: "length", + stop_sequence: None, + termination, + }); + } else { + for tok in full_tokens { + incoming[0].emit_token(tok); + } + incoming[0].emit(GenerationEvent::Finished { + prompt_tokens: incoming[0].prompt.tokens.len(), + generated_tokens: 7, + reused_prompt_tokens: 0, + reason: "stop", + stop_sequence: None, + termination, + }); + } + drop(incoming); + + let response = handle.await.unwrap(); + let is_failed = expected_terminal_event == "response.failed"; + if !stream && is_failed { + assert_eq!( + response.status(), + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + "{label}" + ); + let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); + let err: Value = serde_json::from_slice(&bytes).unwrap(); + assert!( + err["error"]["message"] + .as_str() + .unwrap() + .contains("did not produce a completed tool call") + ); + continue; + } + assert_eq!(response.status(), axum::http::StatusCode::OK, "{label}"); + let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); + if stream { + let text = std::str::from_utf8(&bytes).unwrap(); + let events: Vec = text + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .map(|data| serde_json::from_str(data).unwrap()) + .collect(); + assert_eq!(events[0]["type"], "response.created", "{label}"); + assert_eq!(events[1]["type"], "response.in_progress", "{label}"); + let last = events.last().unwrap(); + assert_eq!(last["type"], expected_terminal_event, "{label}"); + for event in [&events[0], &events[1], last] { + assert_eq!(event["response"]["tools"], declared_tools, "{label}"); + assert_eq!(event["response"]["tool_choice"], tool_choice, "{label}"); + assert_eq!(event["response"]["text"]["format"], text_format, "{label}"); + } + } else { + let body: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + body["status"], + if termination == crate::output::Termination::OutputLimit { + "incomplete" + } else { + "completed" + }, + "{label}" + ); + assert_eq!(body["tools"], declared_tools, "{label}"); + assert_eq!(body["tool_choice"], tool_choice, "{label}"); + assert_eq!(body["text"]["format"], text_format, "{label}"); + } + } + } +} + #[tokio::test] async fn paused_http_bodies_preserve_output_and_completion_for_every_protocol() { use axum::{Extension, extract::State};