From cb3ee4d7a6a2ebc082ed8b1a776c7a4bed57c373 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 4 Oct 2026 23:12:09 +0200 Subject: [PATCH] feat(responses): support forced top-level custom tools --- control-plane/src/responses.rs | 76 ++++++++++++++++++++++++++-------- docs/api-contract.md | 12 ++++-- scripts/smoke-tool-policy.py | 71 ++++++++++++++++++++++++++----- 3 files changed, 129 insertions(+), 30 deletions(-) diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 7bb7026f..32b42559 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -239,10 +239,10 @@ pub enum TextFormat { } impl CreateRequest { - fn forced_function(&self) -> Option<&str> { + fn forced_tool(&self) -> Option<&str> { self.tool_choice .as_ref() - .filter(|choice| choice["type"] == "function")? + .filter(|choice| choice["type"] == "function" || choice["type"] == "custom")? .get("name")? .as_str() } @@ -251,7 +251,7 @@ impl CreateRequest { self.tool_choice .as_ref() .is_some_and(|choice| choice == "required") - || self.forced_function().is_some() + || self.forced_tool().is_some() } fn tools_disabled(&self) -> bool { @@ -267,8 +267,8 @@ 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()); + if self.forced_tool().is_some() && count > 1 { + return Err("forced tool choice permits exactly one tool call".into()); } Ok(()) } @@ -347,17 +347,17 @@ impl CreateRequest { )); } if let Some(choice) = &self.tool_choice - && choice["type"] == "function" + && (choice["type"] == "function" || choice["type"] == "custom") && (choice.as_object().is_none_or(|fields| fields.len() != 2) || !self.tools.iter().any(|tool| { - tool["type"] == "function" + tool["type"] == choice["type"] && 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", + "forced tool needs only type and the name of a declared top-level tool of the same type", )); } let mut names = HashSet::new(); @@ -929,11 +929,20 @@ 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() { + if let Some(name) = request.forced_tool() { + let kind = if request + .tool_choice + .as_ref() + .is_some_and(|choice| choice["type"] == "custom") + { + "custom tool" + } else { + "function" + }; owned.push(( Role::System, format!( - "Call exactly one function in this response: {name}. Do not call any other tool." + "Call exactly one {kind} in this response: {name}. Do not call any other tool." ), None, )); @@ -1964,11 +1973,15 @@ 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" && choice != "required" && choice["type"] != "function" + choice != "auto" + && choice != "none" + && choice != "required" + && choice["type"] != "function" + && choice["type"] != "custom" }) { return Err(( "tool_choice", - "only auto, none, required and forced top-level function choices are connected", + "only auto, none, required and forced top-level function/custom choices are connected", )); } if request @@ -2054,11 +2067,8 @@ impl ResponseTrace { 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()); + if request.forced_tool().is_some_and(|forced| forced != name) { + return Err("generated tool does not match forced tool choice".into()); } } } @@ -2525,6 +2535,38 @@ mod tests { assert!(disabled.validate().is_err()); } + #[test] + fn forced_custom_preserves_input_and_enforces_declared_kind() { + let mut request = make_request(json!({ + "tools":[{"type":"custom","name":"patch","format":{"type":"text"}}], + "tool_choice":{"type":"custom","name":"patch"} + })); + request.validate().unwrap(); + validate_live_subset(&request).unwrap(); + assert!(render_request_prompt(&request).unwrap().contains( + "Call exactly one custom tool in this response: patch. Do not call any other tool." + )); + let input = " Привіт 🌍\n\ttext\n "; + let calls = [OutputItem::FunctionCall { + name: "patch".into(), + call_id: "custom1".into(), + argument_deltas: vec![json!({"input":input}).to_string()], + }]; + let trace = ResponseTrace::build(&request, &calls, usage(), "resp_custom", 1, 2).unwrap(); + assert_eq!(trace.response["output"][0]["type"], "custom_tool_call"); + assert_eq!(trace.response["output"][0]["input"], input); + assert_eq!(trace.response["output"][0]["call_id"], "custom1"); + for choice in [ + json!({"type":"function","name":"patch"}), + json!({"type":"custom","name":"missing"}), + json!({"type":"custom","name":"patch","namespace":"ns"}), + json!({"type":"custom"}), + ] { + request.tool_choice = Some(choice); + assert_eq!(request.validate().unwrap_err().0, "tool_choice"); + } + } + #[tokio::test] async fn console_envelope_namespaced_calls_preserve_identity_and_replay() { let request = make_request(json!({ diff --git a/docs/api-contract.md b/docs/api-contract.md index b97556d2..3f7c648f 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -286,8 +286,8 @@ Native Responses accepts `{"type":"custom","name":"run"}` with an optional string description and optional `"format":{"type":"text"}`. Namespace containers may include custom tools. Regex format has the validation-only preview described below. Lark, unknown custom fields and non-text outputs are -explicitly rejected. `tool_choice` supports `auto` and `none`, as for function -tools; the call-count policy below also applies to custom tools. +explicitly rejected. `tool_choice` supports `auto`, `none`, `required`, and forced top-level custom +tools; see [Tool choice and call count](#tool-choice-and-call-count). Custom calls expose `type: custom_tool_call`, `input`, `name`, `call_id` and optional `namespace`; they never expose the internal JSON `arguments` wrapper. @@ -366,7 +366,13 @@ participate in the same count. 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. +`{"type":"custom","name":"patch"}` likewise forces exactly one declared +top-level custom tool. Its text input is restored without modification; an +optional supported regex format is still validated before publication. The +selector must match the original tool's type, not its internal function lowering. +This [official custom selector example](https://developers.openai.com/cookbook/examples/partners/aws/openai_models_with_amazon_bedrock#44-use-a-custom-text-tool) +uses the same type/name shape. Forced 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. diff --git a/scripts/smoke-tool-policy.py b/scripts/smoke-tool-policy.py index a2e98f89..429967e0 100644 --- a/scripts/smoke-tool-policy.py +++ b/scripts/smoke-tool-policy.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 """CPU HTTP tool-choice and single-call policy acceptance.""" +import copy import hashlib import http.client import importlib.util @@ -54,12 +55,15 @@ done tools = [ {'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object', 'properties': {'key': {'type': 'string'}}, 'required': ['key'], 'additionalProperties': False}}, + {'type': 'custom', 'name': 'patch', 'format': {'type': 'text'}}, {'type': 'namespace', 'name': 'code', 'tools': [{'type': 'custom', 'name': 'run'}]}, ] alias = 'ns_' + hashlib.sha256(b'code/run').hexdigest()[:24] - source = "print('Привіт 🌍')" + source = "print('Привіт 🌍')\n # exact spacing" function_call = '\n\n\nvalue\n\n\n' custom_call = f'\n\n\n{source}\n\n\n' + patch_call = custom_call.replace(alias, 'patch') + forced_custom = {'type': 'custom', 'name': 'patch'} both = function_call + '\n' + custom_call cases = [ ('auto', True, both, 2, True), @@ -85,8 +89,27 @@ done (forced, True, function_call + '\n' + function_call, 2, False), (forced, True, 'OK', 0, False), ]) + cases.extend([ + (forced_custom, True, patch_call, 1, True), + (forced_custom, False, patch_call, 1, True), + (forced_custom, True, function_call, 1, False), + (forced_custom, True, custom_call, 1, False), + (forced_custom, True, patch_call + '\n' + patch_call, 2, False), + (forced_custom, True, patch_call + '\n' + function_call, 2, False), + (forced_custom, True, 'OK', 0, False), + ]) cases = [(*case, 'stop') for case in cases] - cases.extend((choice, True, 'OK', 0, True, 'length') for choice in ['required', forced]) + cases.extend((choice, True, 'OK', 0, True, 'length') for choice in ['required', forced, forced_custom]) + cases.extend([ + (forced_custom, True, patch_call, 1, True, 'length'), + (forced_custom, True, function_call, 1, False, 'length'), + (forced_custom, True, patch_call + '\n' + patch_call, 2, False, 'length'), + ]) + cases = [(*case, False) for case in cases] + cases.extend([ + (forced_custom, True, patch_call, 1, True, 'stop', True), + (forced_custom, True, patch_call.replace(source, 'FORBIDDEN'), 1, False, 'stop', True), + ]) with tempfile.TemporaryFile() as logs: process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True) try: @@ -102,7 +125,7 @@ done total = 0 for effort in ['none', 'low']: for stream in [False, True]: - for choice, parallel, output, count, valid, reason in cases: + for choice, parallel, output, count, valid, reason, regex in cases: data = (('Think.\n\n' if effort == 'low' else '') + output).encode() # An early failed SSE response can precede the worker's # final read/EOF. Never truncate the inode cat is reading: @@ -117,6 +140,11 @@ done payload['tool_choice'] = choice if parallel is not None: payload['parallel_tool_calls'] = parallel + expected_tools = copy.deepcopy(tools) + if regex: + expected_tools[1]['format'] = {'type': 'grammar', 'syntax': 'regex', + 'definition': r"print\('Привіт 🌍'\)\n # exact spacing"} + payload['tools'] = expected_tools code, body = request('/v1/responses', payload) total += 1 if stream: @@ -127,9 +155,17 @@ done 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 != 'none' and effort == 'none' and output.startswith(function_call) else 0 + allowed = int(effort == 'none' and ( + (choice == forced_custom and output.startswith(patch_call)) or + (choice not in ('none', forced_custom) and output.startswith(function_call)))) assert len(published) == allowed, body - assert not any('custom_tool_call_input' in e['type'] for e in events), body + inputs = [e for e in events if 'custom_tool_call_input' in e['type']] + if choice == forced_custom and allowed: + assert published[0]['name'] == 'patch' + assert ''.join(e['delta'] for e in inputs if e['type'].endswith('.delta')) == source + assert [e['input'] for e in inputs if e['type'].endswith('.done')] == [source] + else: + assert not inputs, body continue assert len(published) == count result = events[-1]['response'] @@ -142,12 +178,20 @@ done 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'} + assert result['tools'] == expected_tools and result['metadata'] == {'fixture': 'policy'} calls = [item for item in result['output'] if item['type'] in ('function_call', 'custom_tool_call')] assert len(calls) == count for call in calls: if call['type'] == 'custom_tool_call': - assert call['input'] == source and call['name'] == 'run' and call['namespace'] == 'code' + assert call['input'] == source + if choice == forced_custom: + assert call['name'] == 'patch' and 'namespace' not in call + if stream: + assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source + assert [e['input'] for e in events if e['type'] == 'response.custom_tool_call_input.done'] == [source] + assert [i['call_id'] for i in published] == [call['call_id']] + else: + assert call['name'] == 'run' and call['namespace'] == 'code' else: assert json.loads(call['arguments']) == {'key': 'value'} if count == 0: @@ -161,12 +205,19 @@ done {'tool_choice': {'type': 'function', 'name': 1}}, {'tool_choice': {**forced, 'namespace': 'code'}}, {'tool_choice': forced, 'tools': [{'type': 'custom', 'name': 'lookup'}]}, + {'tool_choice': {'type': 'custom'}}, + {'tool_choice': {'type': 'custom', 'name': 'missing'}}, + {'tool_choice': {'type': 'custom', 'name': alias}}, + {'tool_choice': {'type': 'custom', 'name': 'run'}}, + {'tool_choice': {'type': 'custom', 'name': 1}}, + {'tool_choice': {'type': 'custom', 'name': 'lookup'}}, + {'tool_choice': {**forced_custom, 'namespace': 'code'}}, ]: assert request('/v1/responses', {**payload, **invalid})[0] == 400, invalid - for unsupported in [{'type': 'allowed_tools', 'mode': 'auto', 'tools': []}, {'type': 'custom', 'name': 'run'}]: + for unsupported in [{'type': 'allowed_tools', 'mode': 'auto', 'tools': []}]: payload['tool_choice'] = unsupported assert request('/v1/responses', payload)[0] == 501 - assert json.loads(request('/metrics')[1])['generation']['started'] == total == 84 + assert json.loads(request('/metrics')[1])['generation']['started'] == total == 136 except Exception: logs.seek(0) print('Synthetic tool-policy worker log:', logs.read().decode(errors='replace'), file=sys.stderr) @@ -178,7 +229,7 @@ done except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() - 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') + print('Tool policy: 136 CPU HTTP cases passed; auto/none/required/forced, single-call, incomplete, mixed tools, reasoning, JSON/SSE, 15 malformed choices, metadata and exact accepted input') if __name__ == '__main__':