From 413b6988fd2cf95cd3fdadf23de7c56657aa8dbf Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 4 Oct 2026 09:51:39 +0200 Subject: [PATCH] feat(responses): enforce required and forced function choice --- .github/workflows/linux.yml | 2 +- control-plane/src/responses.rs | 127 ++++++++++++++++-- docs/api-contract.md | 24 +++- docs/experiments/2026-10-04-required-tools.md | 55 ++++++++ scripts/smoke-tool-policy.py | 41 +++++- 5 files changed, 225 insertions(+), 24 deletions(-) create mode 100644 docs/experiments/2026-10-04-required-tools.md diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index b323373b..b967dd76 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -94,7 +94,7 @@ jobs: run: python3 scripts/smoke-native-auth.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Native custom text and regex tools without GPU run: python3 scripts/smoke-custom-tools.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - - name: Native tool-choice and single-call policy without GPU + - name: Native auto/none/required/forced tool policy without GPU run: python3 scripts/smoke-tool-policy.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Stored Responses retrieval and deletion without GPU run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 3d6a9dca..7bb7026f 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -239,6 +239,21 @@ pub enum TextFormat { } impl CreateRequest { + fn forced_function(&self) -> Option<&str> { + self.tool_choice + .as_ref() + .filter(|choice| choice["type"] == "function")? + .get("name")? + .as_str() + } + + fn tools_required(&self) -> bool { + self.tool_choice + .as_ref() + .is_some_and(|choice| choice == "required") + || self.forced_function().is_some() + } + fn tools_disabled(&self) -> bool { self.tool_choice .as_ref() @@ -252,6 +267,9 @@ impl CreateRequest { if self.parallel_tool_calls == Some(false) && count > 1 { return Err("parallel_tool_calls false permits at most one tool call".into()); } + if self.forced_function().is_some() && count > 1 { + return Err("forced function choice permits exactly one tool call".into()); + } Ok(()) } @@ -322,6 +340,26 @@ impl CreateRequest { return Err(("prompt_cache_key", "cache key exceeds 512 bytes")); } let catalog = Catalog::new(&self.tools).map_err(|message| ("tools", message))?; + if self.tools_required() && catalog.flat.is_empty() { + return Err(( + "tool_choice", + "required tool choice needs at least one callable tool", + )); + } + if let Some(choice) = &self.tool_choice + && choice["type"] == "function" + && (choice.as_object().is_none_or(|fields| fields.len() != 2) + || !self.tools.iter().any(|tool| { + tool["type"] == "function" + && choice["name"].is_string() + && tool["name"] == choice["name"] + })) + { + return Err(( + "tool_choice", + "forced function needs only type and the name of a declared top-level function", + )); + } let mut names = HashSet::new(); for tool in &catalog.flat { let Some(name) = tool.get("name").and_then(Value::as_str) else { @@ -891,6 +929,21 @@ fn render_request_prompt(request: &CreateRequest) -> Result { if let Some(instructions) = &request.instructions { owned.push((Role::System, instructions.clone(), None)); } + if let Some(name) = request.forced_function() { + owned.push(( + Role::System, + format!( + "Call exactly one function in this response: {name}. Do not call any other tool." + ), + None, + )); + } else if request.tools_required() { + owned.push(( + Role::System, + "Call at least one tool in this response.".to_owned(), + None, + )); + } if request.parallel_tool_calls == Some(false) && !request.tools_disabled() && !request.tools.is_empty() @@ -1667,7 +1720,7 @@ fn stream_live_tools( NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) ); let created_at = now.as_secs(); - let initial = ResponseTrace::build( + let initial = ResponseTrace::build_with_terminal( &request, &[OutputItem::Text { deltas: vec![] }], Usage { @@ -1679,6 +1732,7 @@ fn stream_live_tools( &id, created_at, created_at, + true, ) .expect("validated request has a valid initial trace"); let pending_response = initial.events[0]["response"].clone(); @@ -1909,14 +1963,12 @@ async fn send_stream_event( } fn validate_live_subset(request: &CreateRequest) -> Result<(), (&'static str, &'static str)> { - if request - .tool_choice - .as_ref() - .is_some_and(|choice| choice != "auto" && choice != "none") - { + if request.tool_choice.as_ref().is_some_and(|choice| { + choice != "auto" && choice != "none" && choice != "required" && choice["type"] != "function" + }) { return Err(( "tool_choice", - "only auto and none tool choice are connected", + "only auto, none, required and forced top-level function choices are connected", )); } if request @@ -1998,12 +2050,22 @@ impl ResponseTrace { request .validate() .map_err(|(param, message)| format!("{param}: {message}"))?; - request.validate_tool_count( - items - .iter() - .filter(|item| matches!(item, OutputItem::FunctionCall { .. })) - .count(), - )?; + let mut call_count = 0; + for item in items { + if let OutputItem::FunctionCall { name, .. } = item { + call_count += 1; + if request + .forced_function() + .is_some_and(|forced| forced != name) + { + return Err("generated tool does not match forced function choice".into()); + } + } + } + request.validate_tool_count(call_count)?; + if !incomplete && request.tools_required() && call_count == 0 { + return Err("required tool choice produced no tool call".into()); + } if items.is_empty() { return Err("a completed response needs an output item".to_owned()); } @@ -2361,6 +2423,45 @@ mod tests { }, ]; assert!(ResponseTrace::build(&request, &calls, usage(), "resp_policy", 1, 2).is_ok()); + let mut required = request.clone(); + required.tool_choice = Some(json!("required")); + let text = [OutputItem::Text { + deltas: vec!["OK".into()], + }]; + assert!( + render_request_prompt(&required) + .unwrap() + .contains("Call at least one tool") + ); + assert!(ResponseTrace::build(&required, &calls, usage(), "resp_policy", 1, 2).is_ok()); + assert!(ResponseTrace::build(&required, &text, usage(), "resp_policy", 1, 2).is_err()); + assert!( + ResponseTrace::build_with_terminal( + &required, + &text, + usage(), + "resp_policy", + 1, + 2, + true + ) + .is_ok() + ); + let mut forced = request.clone(); + forced.tool_choice = Some(json!({"type":"function", "name":"lookup"})); + assert!( + render_request_prompt(&forced) + .unwrap() + .contains("Call exactly one function in this response: lookup.") + ); + assert!(ResponseTrace::build(&forced, &calls[..1], usage(), "resp_policy", 1, 2).is_ok()); + assert!(ResponseTrace::build(&forced, &calls[1..], usage(), "resp_policy", 1, 2).is_err()); + assert!(ResponseTrace::build(&forced, &calls, usage(), "resp_policy", 1, 2).is_err()); + assert!(ResponseTrace::build(&forced, &text, usage(), "resp_policy", 1, 2).is_err()); + assert!( + ResponseTrace::build_with_terminal(&forced, &text, usage(), "resp_policy", 1, 2, true) + .is_ok() + ); let mut single = request.clone(); single.parallel_tool_calls = Some(false); assert!( diff --git a/docs/api-contract.md b/docs/api-contract.md index 4a0434b3..2dcf055a 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -356,13 +356,31 @@ with no declared tools remains text, as in the existing no-tools path. response, across all namespaces. Prompt guidance asks for at most one call; the server enforces the count. Default/true permits multiple calls. These wire semantics follow the official [tool-choice and parallel-call documentation](https://developers.openai.com/api/docs/guides/function-calling#tool-choice). -Required, forced named and allowed-tools choices remain explicitly unsupported -(501); no choice is silently replaced with auto. + +`"required"` requires at least one function/custom call at successful completion. +It needs a nonempty callable catalog (400 otherwise); together with +`parallel_tool_calls: false` it requires exactly one call. Namespaced calls +participate in the same count. + +`{"type":"function","name":"lookup"}` forces exactly one call to the declared +top-level function `lookup`, regardless of the parallel flag. Missing/unknown +names, custom tools selected as functions and extra selector fields fail with +400 before inference. A name is never treated as an internal namespace alias. +Forced custom/namespaced selectors and `allowed_tools` remain unsupported. +Unsupported choice kinds return 501; no choice is silently replaced with auto. + +Both policies add prompt guidance while retaining declarations and history. +Their minimum count applies only to successful completion: a token-limit +`incomplete` response may contain no complete call. Wrong names and excessive +counts remain invalid even for incomplete responses. Initial streaming envelopes +are not subjected to a completion minimum. Original choice metadata is echoed. Buffered output that violates the policy fails with 502 before any callable output is returned. In ordinary live SSE, a first valid call may already have been published: a second call is rejected before its item/argument/input events, -and the stream ends with `response.failed`. Under none, no callable item is +and the stream ends with `response.failed`. Forced choice rejects a wrong first +call before publishing it; required choice with zero calls fails at completion. +Under none, no callable item is published. Earlier valid text/calls cannot be retracted. Reasoning/structured paths keep their existing buffering behavior. The runtime does not truncate, repair or retry tool calls; these policies do not implement constrained sampling diff --git a/docs/experiments/2026-10-04-required-tools.md b/docs/experiments/2026-10-04-required-tools.md new file mode 100644 index 00000000..400dbfd4 --- /dev/null +++ b/docs/experiments/2026-10-04-required-tools.md @@ -0,0 +1,55 @@ +# Required and forced function choice — STRA-32 + +Date: 2026-10-04. The native Responses candidate adds `tool_choice: "required"` +and the documented top-level function selector +`{"type":"function","name":"lookup"}`. Required permits one or more calls; +combined with `parallel_tool_calls: false`, it permits exactly one. Forced +function choice permits exactly one call to the selected function. + +The model receives prompt guidance. The runtime validates generated calls before +publishing callable items and checks the minimum at successful completion. +There is no constrained sampling or automatic retry. Token-limit incomplete +responses may contain zero complete calls. Wrong names and excessive counts +are still rejected. Ordinary SSE can publish valid text or a first valid call +before a later failure; those events cannot be retracted. + +The selector must contain only type/name and identify a declared top-level +function. Invalid selectors or a required choice with no callable tools fail +before generation. Custom/namespaced forced selectors and allowed-tools remain +unsupported. Original request metadata, tool arguments and historical replay +are retained. See the [API contract](../api-contract.md#tool-choice-and-call-count) +and [official tool-choice semantics](https://developers.openai.com/api/docs/guides/function-calling#tool-choice). + +## Verification + +- Rust 1.99.0: 141 library tests passed, including prompt guidance, required + missing-call rejection, forced wrong-call rejection and incomplete exemption. + Clippy all-targets with warnings denied, fmt and diff checks passed. +- The extended `scripts/smoke-tool-policy.py` passed on macOS debug and Linux + x86_64 musl release, with 84 HTTP generations on each: + auto/default, none, required and forced choices; zero/one/mixed/duplicate calls; + parallel false; token-limit incomplete; JSON/SSE crossed with reasoning + none/low. Eight malformed request configurations fail with 400 before + generation; two unsupported choice kinds fail with 501. Generation metrics + confirm no additional worker requests for rejected configurations. +- Accepted Unicode custom input, function arguments and metadata match the + synthetic baseline exactly (zero tolerance). Invalid output returns JSON 502 + or terminal SSE `response.failed`; sequence numbers are contiguous. Forbidden + call/input events are never published. Completed versus incomplete status is + preserved. +- Linux CI invokes the expanded matrix. Hosted GitHub Actions has not run. + +This is a CPU-verified development candidate awaiting independent QA and real +model qualification. No speedup, model policy-following quality or sustained +stability is claimed. The qualified GPU user trial and tunnel remain unchanged; +readiness does not prove the trial has no active requests. + +## Private artifact + +`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-required-tools-preview`, +**17,440,536 bytes**, SHA-256 +`1c2fdcf7ef92286b518fd67ba66c893f1fcff947f483849bdb041c77e126f732`. +The adjacent private JSON records source revision and checks. This is the Rust +supervisor candidate; its external worker and tokenizer remain deployment +inputs. No active profile or service was upgraded. Owned CPU fixture files and +release intermediates were removed after verification. diff --git a/scripts/smoke-tool-policy.py b/scripts/smoke-tool-policy.py index 76f1e1d3..d2be2c9b 100644 --- a/scripts/smoke-tool-policy.py +++ b/scripts/smoke-tool-policy.py @@ -72,6 +72,21 @@ done ('none', True, custom_call, 1, False), ('none', False, both, 2, False), ] + forced = {'type': 'function', 'name': 'lookup'} + cases.extend([ + ('required', True, 'OK', 0, False), + ('required', True, function_call, 1, True), + ('required', True, custom_call, 1, True), + ('required', True, both, 2, True), + ('required', False, both, 2, False), + (forced, True, function_call, 1, True), + (forced, True, custom_call, 1, False), + (forced, True, both, 2, False), + (forced, True, function_call + '\n' + function_call, 2, False), + (forced, True, 'OK', 0, False), + ]) + cases = [(*case, 'stop') for case in cases] + cases.extend((choice, True, 'OK', 0, True, 'length') for choice in ['required', forced]) with tempfile.TemporaryFile() as logs: process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True) try: @@ -87,9 +102,9 @@ done total = 0 for effort in ['none', 'low']: for stream in [False, True]: - for choice, parallel, output, count, valid in cases: + for choice, parallel, output, count, valid, reason in cases: data = (('Think.\n\n' if effort == 'low' else '') + output).encode() - (root / 'next').write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n') + (root / 'next').write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 {reason}\n') payload = {'model': 'fixture', 'input': 'Use policy', 'max_output_tokens': 1024, 'reasoning': {'effort': effort}, 'stream': stream, 'tools': tools, 'metadata': {'fixture': 'policy'}} @@ -103,11 +118,11 @@ done assert code == 200, (code, body) events = [json.loads(line[5:]) for line in body.splitlines() if line.startswith('data:')] assert [e['sequence_number'] for e in events] == list(range(len(events))) - assert events[-1]['type'] == ('response.completed' if valid else 'response.failed'), body + assert events[-1]['type'] == (('response.incomplete' if reason == 'length' else 'response.completed') if valid else 'response.failed'), body published = [e['item'] for e in events if e['type'] == 'response.output_item.added' and e['item']['type'] in ('function_call', 'custom_tool_call')] if not valid: - allowed = 1 if choice == 'auto' and effort == 'none' else 0 + allowed = 1 if choice != 'none' and effort == 'none' and output.startswith(function_call) else 0 assert len(published) == allowed, body assert not any('custom_tool_call_input' in e['type'] for e in events), body continue @@ -119,6 +134,7 @@ done continue assert code == 200, (code, body) result = json.loads(body) + assert result['status'] == ('incomplete' if reason == 'length' else 'completed') assert result['tool_choice'] == (choice or 'auto') assert result['parallel_tool_calls'] == (parallel if parallel is not None else True) assert result['tools'] == tools and result['metadata'] == {'fixture': 'policy'} @@ -131,10 +147,21 @@ done assert json.loads(call['arguments']) == {'key': 'value'} if count == 0: assert result['output'][-1]['content'][0]['text'] == 'OK' - for unsupported in ['required', {'type': 'function', 'name': 'lookup'}]: + for invalid in [ + {'tool_choice': 'required', 'tools': []}, + {'tool_choice': 'required', 'tools': [{'type': 'namespace', 'name': 'empty', 'tools': []}]}, + {'tool_choice': {'type': 'function'}}, + {'tool_choice': {'type': 'function', 'name': 'missing'}}, + {'tool_choice': {'type': 'function', 'name': alias}}, + {'tool_choice': {'type': 'function', 'name': 1}}, + {'tool_choice': {**forced, 'namespace': 'code'}}, + {'tool_choice': forced, 'tools': [{'type': 'custom', 'name': 'lookup'}]}, + ]: + assert request('/v1/responses', {**payload, **invalid})[0] == 400, invalid + for unsupported in [{'type': 'allowed_tools', 'mode': 'auto', 'tools': []}, {'type': 'custom', 'name': 'run'}]: payload['tool_choice'] = unsupported assert request('/v1/responses', payload)[0] == 501 - assert json.loads(request('/metrics')[1])['generation']['started'] == total == 36 + assert json.loads(request('/metrics')[1])['generation']['started'] == total == 84 finally: process.terminate() try: @@ -142,7 +169,7 @@ done except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() - print('Tool policy: 36 CPU HTTP cases passed; none, single-call, auto/default, mixed tools, reasoning, JSON/SSE, metadata and exact accepted input') + print('Tool policy: 84 CPU HTTP cases passed; auto/none/required/forced, single-call, incomplete, mixed tools, reasoning, JSON/SSE, 8 malformed choices, metadata and exact accepted input') if __name__ == '__main__':