Skip to content

Commit 1cdfb7c

Browse files
authored
fix: normalize named tool_choice to required + filtered tools for OpenAI-compatible providers (#528)
LM Studio (and Ollama) reject the named tool_choice dict format {"type": "function", "function": {"name": "..."}} with HTTP 400. The reflect agent uses this format on iterations 0-2 to force sequential tool selection, causing reflect to fail entirely on LM Studio. The fix converts named tool_choice dicts to tool_choice="required" with the tools list filtered to just the requested tool — semantically identical and accepted by all providers including LM Studio and Ollama. Closes #520
1 parent 3e967ad commit 1cdfb7c

2 files changed

Lines changed: 334 additions & 0 deletions

File tree

hindsight-api/hindsight_api/engine/providers/openai_compatible_llm.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,19 @@ async def call_with_tools(
522522
"""
523523
start_time = time.time()
524524

525+
# Normalize named tool_choice dicts to "required" + filter tools.
526+
# Some providers (e.g. LM Studio, Ollama) reject the OpenAI named format
527+
# {"type": "function", "function": {"name": "..."}}. The semantics are
528+
# identical to tool_choice="required" with the tools list restricted to
529+
# just the requested tool, so we apply that transformation universally.
530+
if isinstance(tool_choice, dict) and tool_choice.get("type") == "function":
531+
forced_name = tool_choice.get("function", {}).get("name")
532+
if forced_name:
533+
filtered = [t for t in tools if t.get("function", {}).get("name") == forced_name]
534+
if filtered:
535+
tools = filtered
536+
tool_choice = "required"
537+
525538
# Build call parameters
526539
call_params: dict[str, Any] = {
527540
"model": self.model,
Lines changed: 321 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,321 @@
1+
"""
2+
Reproduce issue #520: Reflect fails with LM Studio due to unsupported tool_choice format.
3+
4+
The reflect agent forces tool selection via named tool_choice dicts on the first few iterations:
5+
{"type": "function", "function": {"name": "search_mental_models"}}
6+
7+
LM Studio (and Ollama) reject this format with HTTP 400:
8+
"Tool choice of type 'function' is not supported. Use 'auto', 'none', or 'required'."
9+
10+
The fix should convert named tool_choice to "required" and filter the tools list
11+
to only the requested tool for providers that don't support named tool_choice.
12+
"""
13+
14+
import json
15+
from unittest.mock import AsyncMock, MagicMock, patch
16+
17+
import pytest
18+
from openai import APIStatusError
19+
20+
from hindsight_api.engine.providers.openai_compatible_llm import OpenAICompatibleLLM
21+
22+
# Reflect agent tools (subset matching what agent.py uses)
23+
REFLECT_TOOLS = [
24+
{
25+
"type": "function",
26+
"function": {
27+
"name": "search_mental_models",
28+
"description": "Search consolidated mental models",
29+
"parameters": {
30+
"type": "object",
31+
"properties": {"query": {"type": "string"}},
32+
"required": ["query"],
33+
},
34+
},
35+
},
36+
{
37+
"type": "function",
38+
"function": {
39+
"name": "search_observations",
40+
"description": "Search raw observations",
41+
"parameters": {
42+
"type": "object",
43+
"properties": {"query": {"type": "string"}},
44+
"required": ["query"],
45+
},
46+
},
47+
},
48+
{
49+
"type": "function",
50+
"function": {
51+
"name": "recall",
52+
"description": "Recall semantic memories",
53+
"parameters": {
54+
"type": "object",
55+
"properties": {"query": {"type": "string"}},
56+
"required": ["query"],
57+
},
58+
},
59+
},
60+
{
61+
"type": "function",
62+
"function": {
63+
"name": "done",
64+
"description": "Finish and return the answer",
65+
"parameters": {
66+
"type": "object",
67+
"properties": {"answer": {"type": "string"}},
68+
"required": ["answer"],
69+
},
70+
},
71+
},
72+
]
73+
74+
75+
def _make_lmstudio_llm() -> OpenAICompatibleLLM:
76+
return OpenAICompatibleLLM(
77+
provider="lmstudio",
78+
api_key="local",
79+
base_url="http://localhost:1234/v1",
80+
model="openai/gpt-oss-20b",
81+
)
82+
83+
84+
def _lmstudio_400_error(msg: str = "Tool choice of type 'function' is not supported. Use 'auto', 'none', or 'required'.") -> APIStatusError:
85+
"""Simulate the HTTP 400 LM Studio returns for unsupported tool_choice format."""
86+
mock_response = MagicMock()
87+
mock_response.status_code = 400
88+
mock_response.headers = {}
89+
return APIStatusError(
90+
message=msg,
91+
response=mock_response,
92+
body={"error": {"message": msg, "type": "invalid_request_error"}},
93+
)
94+
95+
96+
def _make_tool_call_response(tool_name: str, arguments: dict) -> MagicMock:
97+
"""Build a mock successful tool call response from the LLM API."""
98+
mock_tc = MagicMock()
99+
mock_tc.id = "call_abc123"
100+
mock_tc.function.name = tool_name
101+
mock_tc.function.arguments = json.dumps(arguments)
102+
103+
mock_response = MagicMock()
104+
mock_response.usage.prompt_tokens = 120
105+
mock_response.usage.completion_tokens = 40
106+
mock_response.usage.total_tokens = 160
107+
mock_response.choices[0].finish_reason = "tool_calls"
108+
mock_response.choices[0].message.content = None
109+
mock_response.choices[0].message.tool_calls = [mock_tc]
110+
return mock_response
111+
112+
113+
class TestLMStudioNamedToolChoiceBug:
114+
"""
115+
Reproduces issue #520.
116+
117+
The reflect agent (agent.py lines 546-555) sets tool_choice to a named dict
118+
on the first iterations to force sequential retrieval:
119+
120+
iteration=0, has_mental_models=True → {"type": "function", "function": {"name": "search_mental_models"}}
121+
iteration=0, has_mental_models=False → {"type": "function", "function": {"name": "search_observations"}}
122+
iteration=1, has_mental_models=True → {"type": "function", "function": {"name": "search_observations"}}
123+
iteration=1 or (2 with models) → {"type": "function", "function": {"name": "recall"}}
124+
125+
LM Studio rejects these dict formats with HTTP 400.
126+
"""
127+
128+
@pytest.mark.asyncio
129+
async def test_lmstudio_named_tool_choice_no_longer_causes_400(self):
130+
"""
131+
Regression test for issue #520: named tool_choice dict is converted to
132+
"required" + filtered tools before the API call, so LM Studio never
133+
sees the unsupported format and the 400 error no longer occurs.
134+
"""
135+
llm = _make_lmstudio_llm()
136+
named_tool_choice = {"type": "function", "function": {"name": "search_mental_models"}}
137+
success_response = _make_tool_call_response("search_mental_models", {"query": "user name"})
138+
139+
with patch.object(llm._client.chat.completions, "create", new_callable=AsyncMock) as mock_create:
140+
mock_create.return_value = success_response
141+
142+
# Should succeed — no 400 because the dict is converted before sending
143+
result = await llm.call_with_tools(
144+
messages=[{"role": "user", "content": "What is the user's name?"}],
145+
tools=REFLECT_TOOLS,
146+
tool_choice=named_tool_choice,
147+
max_retries=0,
148+
)
149+
150+
assert len(result.tool_calls) == 1
151+
assert result.tool_calls[0].name == "search_mental_models"
152+
153+
sent_kwargs = mock_create.call_args.kwargs
154+
assert sent_kwargs["tool_choice"] == "required"
155+
assert len(sent_kwargs["tools"]) == 1
156+
assert sent_kwargs["tools"][0]["function"]["name"] == "search_mental_models"
157+
158+
@pytest.mark.asyncio
159+
@pytest.mark.parametrize(
160+
"forced_tool_name",
161+
["search_mental_models", "search_observations", "recall"],
162+
)
163+
async def test_all_reflect_forced_tools_fail_on_lmstudio(self, forced_tool_name: str):
164+
"""
165+
Each named tool_choice the reflect agent uses on iterations 0-2 triggers
166+
the same 400 error on LM Studio.
167+
"""
168+
llm = _make_lmstudio_llm()
169+
named_tool_choice = {"type": "function", "function": {"name": forced_tool_name}}
170+
171+
with patch.object(llm._client.chat.completions, "create", new_callable=AsyncMock) as mock_create:
172+
mock_create.side_effect = _lmstudio_400_error()
173+
174+
with pytest.raises(APIStatusError) as exc_info:
175+
await llm.call_with_tools(
176+
messages=[{"role": "user", "content": "Test query"}],
177+
tools=REFLECT_TOOLS,
178+
tool_choice=named_tool_choice,
179+
max_retries=0,
180+
)
181+
182+
assert exc_info.value.status_code == 400
183+
184+
@pytest.mark.asyncio
185+
async def test_lmstudio_string_tool_choice_works_fine(self):
186+
"""
187+
String tool_choice values ("auto", "none", "required") ARE supported by LM Studio.
188+
Only the dict format {"type": "function", "function": {"name": "..."}} fails.
189+
This test confirms the control case works.
190+
"""
191+
llm = _make_lmstudio_llm()
192+
success_response = _make_tool_call_response("search_mental_models", {"query": "user name"})
193+
194+
with patch.object(llm._client.chat.completions, "create", new_callable=AsyncMock) as mock_create:
195+
mock_create.return_value = success_response
196+
197+
result = await llm.call_with_tools(
198+
messages=[{"role": "user", "content": "What is the user's name?"}],
199+
tools=REFLECT_TOOLS,
200+
tool_choice="required", # string form — LM Studio accepts this
201+
max_retries=0,
202+
)
203+
204+
assert len(result.tool_calls) == 1
205+
assert result.tool_calls[0].name == "search_mental_models"
206+
207+
# Confirm "required" was sent, not a dict
208+
sent_kwargs = mock_create.call_args.kwargs
209+
assert sent_kwargs["tool_choice"] == "required"
210+
211+
212+
class TestExpectedFixBehavior:
213+
"""
214+
Tests that document the EXPECTED behavior after the fix is applied.
215+
216+
For lmstudio (and ollama) providers, when tool_choice is a named dict:
217+
{"type": "function", "function": {"name": "search_mental_models"}}
218+
219+
The fix should:
220+
1. Convert tool_choice to "required"
221+
2. Filter tools to only the requested tool
222+
223+
These tests currently FAIL (because the fix is not yet implemented).
224+
After the fix is applied, they should PASS.
225+
"""
226+
227+
@pytest.mark.asyncio
228+
async def test_fix_converts_named_tool_choice_to_required(self):
229+
"""
230+
After fix: named tool_choice dict is converted to "required" for lmstudio.
231+
The API receives tool_choice="required" instead of the unsupported dict.
232+
"""
233+
llm = _make_lmstudio_llm()
234+
named_tool_choice = {"type": "function", "function": {"name": "search_mental_models"}}
235+
success_response = _make_tool_call_response("search_mental_models", {"query": "user name"})
236+
237+
with patch.object(llm._client.chat.completions, "create", new_callable=AsyncMock) as mock_create:
238+
mock_create.return_value = success_response
239+
240+
result = await llm.call_with_tools(
241+
messages=[{"role": "user", "content": "What is the user's name?"}],
242+
tools=REFLECT_TOOLS,
243+
tool_choice=named_tool_choice,
244+
max_retries=0,
245+
)
246+
247+
assert len(result.tool_calls) == 1
248+
assert result.tool_calls[0].name == "search_mental_models"
249+
250+
sent_kwargs = mock_create.call_args.kwargs
251+
# Fix: dict was converted to "required"
252+
assert sent_kwargs["tool_choice"] == "required", (
253+
f"Expected tool_choice='required', got {sent_kwargs['tool_choice']!r}"
254+
)
255+
# Fix: tools filtered to just the requested one
256+
assert len(sent_kwargs["tools"]) == 1
257+
assert sent_kwargs["tools"][0]["function"]["name"] == "search_mental_models"
258+
259+
@pytest.mark.asyncio
260+
@pytest.mark.parametrize(
261+
"forced_tool_name",
262+
["search_mental_models", "search_observations", "recall"],
263+
)
264+
async def test_fix_filters_tools_to_requested_tool(self, forced_tool_name: str):
265+
"""
266+
After fix: tools list is filtered to only the forced tool so the model
267+
can only call that one tool (equivalent to the named tool_choice behavior).
268+
"""
269+
llm = _make_lmstudio_llm()
270+
named_tool_choice = {"type": "function", "function": {"name": forced_tool_name}}
271+
success_response = _make_tool_call_response(forced_tool_name, {"query": "test"})
272+
273+
with patch.object(llm._client.chat.completions, "create", new_callable=AsyncMock) as mock_create:
274+
mock_create.return_value = success_response
275+
276+
await llm.call_with_tools(
277+
messages=[{"role": "user", "content": "Test query"}],
278+
tools=REFLECT_TOOLS,
279+
tool_choice=named_tool_choice,
280+
max_retries=0,
281+
)
282+
283+
sent_kwargs = mock_create.call_args.kwargs
284+
assert sent_kwargs["tool_choice"] == "required"
285+
assert len(sent_kwargs["tools"]) == 1
286+
assert sent_kwargs["tools"][0]["function"]["name"] == forced_tool_name
287+
288+
@pytest.mark.asyncio
289+
async def test_fix_also_applies_to_openai_provider(self):
290+
"""
291+
The fix is generalized: all providers convert named tool_choice to
292+
"required" + filtered tools. OpenAI natively supports the dict format
293+
too, so the behaviour is semantically identical either way.
294+
"""
295+
from hindsight_api.engine.providers.openai_compatible_llm import OpenAICompatibleLLM
296+
297+
openai_llm = OpenAICompatibleLLM(
298+
provider="openai",
299+
api_key="sk-test",
300+
base_url="",
301+
model="gpt-4o-mini",
302+
)
303+
304+
named_tool_choice = {"type": "function", "function": {"name": "search_mental_models"}}
305+
success_response = _make_tool_call_response("search_mental_models", {"query": "test"})
306+
307+
with patch.object(openai_llm._client.chat.completions, "create", new_callable=AsyncMock) as mock_create:
308+
mock_create.return_value = success_response
309+
310+
await openai_llm.call_with_tools(
311+
messages=[{"role": "user", "content": "Test"}],
312+
tools=REFLECT_TOOLS,
313+
tool_choice=named_tool_choice,
314+
max_retries=0,
315+
)
316+
317+
sent_kwargs = mock_create.call_args.kwargs
318+
# Generalized fix applies to OpenAI too
319+
assert sent_kwargs["tool_choice"] == "required"
320+
assert len(sent_kwargs["tools"]) == 1
321+
assert sent_kwargs["tools"][0]["function"]["name"] == "search_mental_models"

0 commit comments

Comments
 (0)