Skip to content

Commit ffca637

Browse files
fix(content): MiniMax quiz gen — send tool_result correction, not plain text
MiniMax's /anthropic shim rejected quiz generation with HTTP 400 error 2013 ("invalid params, tool call result does not follow tool call") whenever the schema-correction retry fired. Root cause: the AnthropicCompatGenerator retry path appended a plain-text `user` turn after the assistant's `tool_use` turn. Anthropic's own API tolerates this; MiniMax's stricter shim enforces the spec — the user turn after a tool_use MUST carry a `tool_result` block referencing that tool_use id. Fix: `_extract_tool_payload` now also returns the tool_use id; the retry loop appends a protocol-valid `[assistant tool_use, user tool_result]` pair and overwrites the tool_result content with the real validation error on the next attempt. Valid alternation across all Anthropic-compat providers. Proven live: MiniMax M2.7 quiz generation now succeeds (5 cards, 0 errors) against the real shim — previously failed 100% on the correction path. Tests: updated the retry test to assert the tool_result shape + added a MiniMax regression test. 14 passed.
1 parent 51ee08f commit ffca637

2 files changed

Lines changed: 106 additions & 29 deletions

File tree

‎packages/studyloop/src/studyloop/content/generators/anthropic_compat.py‎

Lines changed: 51 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -196,17 +196,29 @@ def _generate(
196196
tool_choice = {"type": "tool", "name": tool_name}
197197

198198
def call(ctx: CallContext) -> tuple[Any, list[dict[str, Any]]]:
199-
messages = list(base_messages) + list(ctx.history_extension)
200-
if ctx.last_error is not None:
201-
messages.append(
202-
{
203-
"role": "user",
204-
"content": (
205-
f"The previous tool call did not validate against the schema: "
206-
f"{ctx.last_error}. Re-emit a corrected payload that conforms."
207-
),
208-
}
209-
)
199+
history = list(ctx.history_extension)
200+
# On a retry, fill in the real validation error on the tool_result
201+
# placeholder that the previous attempt appended. The Anthropic
202+
# Messages spec requires the user turn after an assistant tool_use
203+
# to be a tool_result for that tool_use id; MiniMax's /anthropic
204+
# shim enforces this strictly (a plain-text user turn -> error
205+
# 2013). Carrying the correction AS a tool_result keeps the
206+
# alternation valid across all providers.
207+
if ctx.last_error is not None and history:
208+
last = history[-1]
209+
if (
210+
last.get("role") == "user"
211+
and isinstance(last.get("content"), list)
212+
and last["content"]
213+
and last["content"][0].get("type") == "tool_result"
214+
):
215+
last["content"][0]["content"] = (
216+
f"The previous tool call did not validate against the "
217+
f"schema: {ctx.last_error}. Re-emit a corrected payload "
218+
f"that conforms exactly."
219+
)
220+
221+
messages = list(base_messages) + history
210222

211223
payload: dict[str, Any] = {
212224
"model": self._model.id,
@@ -224,18 +236,27 @@ def call(ctx: CallContext) -> tuple[Any, list[dict[str, Any]]]:
224236
}
225237

226238
resp = self._post_messages(payload)
227-
tool_payload, assistant_turn = self._extract_tool_payload(resp, tool_name)
228-
new_history = list(ctx.history_extension) + [assistant_turn]
229-
if ctx.last_error is not None:
230-
new_history.append(
231-
{
232-
"role": "user",
233-
"content": (
234-
f"The previous tool call did not validate against the schema: "
235-
f"{ctx.last_error}. Re-emit a corrected payload that conforms."
236-
),
237-
}
238-
)
239+
tool_payload, assistant_turn, tool_use_id = self._extract_tool_payload(
240+
resp, tool_name
241+
)
242+
# Append the assistant's tool_use turn followed immediately by a
243+
# placeholder tool_result so the history stays protocol-valid. If
244+
# validation fails, the NEXT attempt overwrites the placeholder
245+
# content with the actual error (above).
246+
new_history = [
247+
*history,
248+
assistant_turn,
249+
{
250+
"role": "user",
251+
"content": [
252+
{
253+
"type": "tool_result",
254+
"tool_use_id": tool_use_id,
255+
"content": "Acknowledged.",
256+
}
257+
],
258+
},
259+
]
239260
return tool_payload, new_history
240261

241262
return call_with_correction(
@@ -266,14 +287,18 @@ def _post_messages(self, payload: dict[str, Any]) -> dict[str, Any]:
266287

267288
def _extract_tool_payload(
268289
self, resp: dict[str, Any], expected_tool_name: str
269-
) -> tuple[dict[str, Any], dict[str, Any]]:
290+
) -> tuple[dict[str, Any], dict[str, Any], str]:
270291
"""Pull the ``tool_use`` block out of an Anthropic Messages response.
271292
272293
Anthropic returns ``content`` as a list of typed blocks. With
273294
forced tool_choice, exactly one of those blocks should be a
274295
``{type:"tool_use", name, input}`` block. We assemble the
275296
assistant turn from the full content list so the correction-turn
276297
history sees what the model actually said.
298+
299+
Returns ``(tool_input, assistant_turn, tool_use_id)``. The
300+
``tool_use_id`` lets the caller build a protocol-valid
301+
``tool_result`` correction turn that references this exact call.
277302
"""
278303
content = resp.get("content")
279304
if not isinstance(content, list) or not content:
@@ -314,7 +339,8 @@ def _extract_tool_payload(
314339
)
315340

316341
assistant_turn = {"role": "assistant", "content": content}
317-
return args, assistant_turn
342+
tool_use_id = str(tool_use_block.get("id") or "toolu_correction")
343+
return args, assistant_turn, tool_use_id
318344

319345

320346
__all__ = ["AnthropicCompatGenerator"]

‎packages/studyloop/tests/test_anthropic_compat_generator.py‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,63 @@ def test_validation_failure_triggers_correction_then_succeeds(self) -> None:
238238
assert route.call_count == 2
239239
second_body = json.loads(route.calls[1].request.content)
240240
messages = second_body["messages"]
241-
assert any(
242-
m.get("role") == "user"
243-
and isinstance(m.get("content"), str)
244-
and "did not validate" in m["content"]
241+
# The correction MUST be delivered as a tool_result block (not a
242+
# plain-text user turn): Anthropic's protocol requires the user turn
243+
# after an assistant tool_use to carry a tool_result for that
244+
# tool_use id. MiniMax's shim enforces this strictly (error 2013).
245+
corrections = [
246+
m
245247
for m in messages
248+
if m.get("role") == "user" and isinstance(m.get("content"), list)
249+
]
250+
assert corrections, "expected a tool_result correction turn"
251+
block = corrections[-1]["content"][0]
252+
assert block["type"] == "tool_result"
253+
assert block["tool_use_id"] == "toolu_1" # references the prior tool_use
254+
assert "did not validate" in block["content"]
255+
# Protocol sanity: every assistant tool_use turn is immediately
256+
# followed by a user tool_result turn (valid alternation).
257+
for i, m in enumerate(messages[:-1]):
258+
if m.get("role") == "assistant" and isinstance(m.get("content"), list):
259+
has_tool_use = any(
260+
b.get("type") == "tool_use" for b in m["content"]
261+
)
262+
if has_tool_use:
263+
nxt = messages[i + 1]
264+
assert nxt["role"] == "user"
265+
assert isinstance(nxt["content"], list)
266+
assert nxt["content"][0]["type"] == "tool_result"
267+
finally:
268+
gen.close()
269+
270+
@pytest.mark.usefixtures("minimax_key")
271+
@respx.mock
272+
def test_minimax_retry_sends_tool_result_not_plain_text(self) -> None:
273+
# Regression for MiniMax error 2013 ("tool call result does not follow
274+
# tool call"): the strict /anthropic shim rejected a plain-text user
275+
# turn after an assistant tool_use. The retry must send a tool_result.
276+
gen = _make_generator("minimax", "MiniMax-M2.7")
277+
try:
278+
bad = {"title": "X"} # missing cards -> validation fails first
279+
good = {"title": "X", "cards": [{"front": "Q?", "back": "A."}]}
280+
route = respx.post("https://api.minimax.io/anthropic/v1/messages").mock(
281+
side_effect=[
282+
httpx.Response(
283+
200, json=_tool_use_response("emit_flashcard_deck", bad)
284+
),
285+
httpx.Response(
286+
200, json=_tool_use_response("emit_flashcard_deck", good)
287+
),
288+
]
246289
)
290+
deck = gen.generate_flashcards(source="x", title="X")
291+
assert deck.title == "X"
292+
second_body = json.loads(route.calls[1].request.content)
293+
# No plain-text user turn allowed after the tool_use.
294+
for m in second_body["messages"]:
295+
if m["role"] == "user" and m is not second_body["messages"][0]:
296+
assert isinstance(m["content"], list)
297+
assert m["content"][0]["type"] == "tool_result"
247298
finally:
248299
gen.close()
249300

0 commit comments

Comments
 (0)