Skip to content

fix: honour tool_choice on /v1/chat/completions - #270

Merged
solderzzc merged 1 commit into
SharpAI:mainfrom
HamedShams:fix/tool-choice
Nov 12, 2026
Merged

solderzzc merged 1 commit into
SharpAI:mainfrom
HamedShams:fix/tool-choice

Conversation

@HamedShams

Copy link
Copy Markdown
Contributor

Closes #269.

tool_choice was never decoded, so every value behaved like auto: with "none" the model still got all the tools and could answer with a tool call, a named function didn't narrow anything, and a typo was a normal 200.

What it does now:

  • none – no tools go to the template. If the model emits a tool call anyway, it's dropped and logged instead of sent back.
  • a named function – only that tool goes to the template, and a call to any other function is dropped the same way.
  • a value the API doesn't have, or a function that isn't in tools – 400 invalid_request_error that names tool_choice.
  • auto, or no tool_choice – same as before.
  • required – still behaves like auto, now with a line in the server log. Really forcing a call needs constrained decoding, so I left that out to keep this one small.

Same requests on main and on this branch (two tools in the request, mlx-community/Qwen2.5-0.5B-Instruct-4bit, M1 Max):

request main this PR
no tools 200, 32 prompt tokens same
tools, no tool_choice 200, 224 same
tools + auto or required 200, 224 same
tools + none 200, 224 200, 32
tools + naming get_time 200, 224 200, 168
tools + "sometimes" 200, 224 400
tools + naming get_stock, which isn't in tools 200, 224 400

Tests:

  • ToolChoiceTests, 15 new: decoding, which tools reach the prompt, the 400s, and both chat handlers dropping a call that the choice ruled out.
  • tests/test-contract.sh block 18: none and a named function show up in prompt_tokens, and the two bad values are a 400. All 4 checks fail on main.
  • swift test --filter SwiftLMTests: 365 tests, 0 failures. Contract suite against the CI model: 32 passed, 0 failed, 2 skipped (the two usual skips for the tiny model).

I also added the tool_choice row to docs/api-response-formats.md.

tool_choice was never decoded, so every value behaved like auto. "none" now keeps the tools out of the prompt and a tool call out of the reply, a named function offers only that tool, and a value the API does not have or a function that is not in tools is a 400 that names tool_choice. "required" is still handled like auto, with a line in the server log.

Closes SharpAI#269.
@solderzzc
solderzzc merged commit 324f67e into SharpAI:main Nov 12, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tool_choice is ignored on /v1/chat/completions

2 participants