hindsight icon indicating copy to clipboard operation
hindsight copied to clipboard

Reflect fails with HTTP 400 on the anthropic provider: "For 'anyOf', 'items' is not supported" (nullable array in done schema)

Open bucketphobia opened this issue 1 month ago • 3 comments

Summary

On 1.2.0, reflect calls through the anthropic LLM provider fail with HTTP 400 when a decision model is on. The native structured output schema contains {"type": ["array", "null"], "items": {...}}. Anthropic reads the type list as anyOf and refuses items beside it:

BadRequestError: Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error',
'message': "output_config.format.schema: For 'anyOf', 'items' is not supported"}}

llm_requests records the failures under operation=reflect, scope=reflect_tool_call. The reflect request then returns HTTP 500.

Environment

  • Image: ghcr.io/vectorize-io/hindsight:1.2.0-slim
  • Reflect LLM: HINDSIGHT_API_REFLECT_LLM_PROVIDER=anthropic, model claude-haiku-5-5 (through an Anthropic-compatible gateway; the gateway forwards output_config unchanged)
  • Decision model: HINDSIGHT_API_DECISION_MODEL_PROVIDER=hindsight or typesafe (also the RECALL_, REFLECT_ and CONSOLIDATION_ variants)

Observed

The test used the same bank and the same 30 reflect queries for each provider:

Decision model Reflects answered reflect_tool_call errors
none 30 / 30 0
hindsight 10 / 30 20 failed reflects (6 of 9 tool calls failed in the sample checked)
typesafe 16 / 30 28 of 44 tool calls

Page refresh (refresh_mental_model) on the same servers had no such errors.

Cause

  1. engine/reflect/tools_schema.py:161 and :235: the done tool declares memory_ids, mental_model_ids and observation_ids as optional arrays.
  2. engine/providers/tools_via_schema.py:50 (_closed): each optional property becomes nullable with prop["type"] = [prop["type"], "null"]. The result is {"type": ["array", "null"], "items": {"type": "string"}}.
  3. engine/llm_wrapper.py:1547: tool calls go through call(..., strict_schema=True), so HINDSIGHT_API_LLM_STRICT_SCHEMA_REFLECT=false does not avoid native output.
  4. engine/providers/anthropic_llm.py:381: _for_native_output(strict_json_schema(...)) removes maxItems, minLength and maxLength, but keeps the type list. Anthropic refuses it.

_with_cited_handles (engine/reflect/agent.py:2284) makes the id fields required, so a done that goes through it is not nullable. Turns whose tool list still has the original done keep the nullable arrays. These turns occurred only with a decision model on in this test. I did not trace why.

Minimal reproduction (no Hindsight needed)

curl -s https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' \
  -d '{"model":"claude-haiku-5-5","max_tokens":64,
       "messages":[{"role":"user","content":"Return ids a and b."}],
       "output_config":{"format":{"type":"json_schema","schema":{
         "type":"object","additionalProperties":false,"required":["ids"],
         "properties":{"ids":{"type":["array","null"],"items":{"type":"string"}}}}}}}'

Result: HTTP 400, For 'anyOf', 'items' is not supported. (I sent this request through the gateway named above, not directly to api.anthropic.com.)

Change ids to {"anyOf":[{"type":"array","items":{"type":"string"}},{"type":"null"}]}. The call then succeeds.

Proposed fix

In engine/providers/anthropic_llm.py, rewrite nullable type lists into anyOf branches before the schema goes into output_config:

_SHARED = {"description", "title", "default"}


def _nullable_as_any_of(node: Any) -> Any:
    """Anthropic reads ``{"type": [X, "null"]}`` as anyOf and refuses X's keywords beside it."""
    if isinstance(node, list):
        return [_nullable_as_any_of(item) for item in node]
    if not isinstance(node, dict):
        return node
    node = {key: _nullable_as_any_of(value) for key, value in node.items()}
    types = node.get("type")
    if isinstance(types, list) and "null" in types and len(types) > 1:
        shared = {key: value for key, value in node.items() if key in _SHARED}
        rest = {key: value for key, value in node.items() if key not in _SHARED and key != "type"}
        branches = [{"type": t, **rest} for t in types if t != "null"] + [{"type": "null"}]
        return {**shared, "anyOf": branches}
    return node
-                schema = _for_native_output(strict_json_schema(response_format))
+                schema = _nullable_as_any_of(_for_native_output(strict_json_schema(response_format)))

Note: this walk also visits the keys of properties. A property named type whose value is a list would match. _for_native_output handles that case with _SUBSCHEMA_NAME_MAPS, and the same guard can apply here.

With this patch mounted over the 1.2.0 image, the same 30 reflects passed for all three decision model settings (90 / 90, 0 reflect_tool_call errors).

Other fixes are possible: the fix could go in _closed, or the reflect loop could always pass done through _with_cited_handles. The provider-level fix also covers every other nullable schema sent to Anthropic.

bucketphobia avatar Nov 03 '26 23:11 bucketphobia

I think I found the "why only with a decision model" part.

In reflect/agent.py (main f14cc1e), the loop turns drop done only when the closing step writes the answer:

closing_step_answers = evidence_is_sufficient_fn is None or answer_as_document
...
loop_tools = tools
if closing_step_answers:
    loop_tools = [t for t in tools if not _is_done_tool(t["function"]["name"])]

With a decision model on (and not a document answer), closing_step_answers is False, so every reflect_tool_call turn carries the original done, not the _with_cited_handles one. That done has the three optional id arrays.

I ran get_reflect_tools and _closed (copied from tools_via_schema.py) for each case and listed any property that ends up as a type list next to items:

Decision model Loop tools Shapes Anthropic refuses
off searches + answer_ready none
on searches + done done.memory_ids, mental_model_ids, observation_ids

That matches your table (0 errors without a decision model). I didn't call Anthropic myself.

A possible fix that keeps other providers as they are: in anthropic_llm._for_native_output, rewrite {"type": [T, "null"], ...} to {"anyOf": [{"type": T, ...}, {"type": "null"}]}, since each anyOf branch can carry its own items. A test that runs the decision-model loop tools through _for_native_output and checks for no type list beside items would keep it fixed.

balabommablock-cpu avatar Nov 04 '26 03:11 balabommablock-cpu

Thanks for the detailed write-up!

We ran your minimal reproduction exactly as written, straight against api.anthropic.com, and it works. Anthropic accepts the nullable array schema:

curl -s https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' \
  -d '{"model":"claude-haiku-5-5","max_tokens":64,
       "messages":[{"role":"user","content":"Return ids a and b."}],
       "output_config":{"format":{"type":"json_schema","schema":{
         "type":"object","additionalProperties":false,"required":["ids"],
         "properties":{"ids":{"type":["array","null"],"items":{"type":"string"}}}}}}}'
Model Result
claude-haiku-5-5 200, {"ids":["a","b"]}
claude-sonnet-5-5 200, {"ids":["a","b"]}

We also sent the full reflect tool-turn schema that current main builds with a decision model on (including done with the nullable memory_ids / mental_model_ids / observation_ids) to api.anthropic.com with claude-haiku-5-5. It also returned 200 with a valid done call.

So the 400 (For 'anyOf', 'items' is not supported) seems to come from the gateway you use. It validates schemas more strictly than Anthropic does. Closing for now. If you can reproduce this directly against api.anthropic.com, or tell us which gateway rejects it (so we can reproduce it), please reopen with that and we'll take another look.

nicoloboschi avatar Nov 06 '26 11:11 nicoloboschi

Not fixed when closed: fixed by #6401 (optional tool arguments are now written as anyOf, not a type list).

nicoloboschi avatar Nov 06 '26 13:11 nicoloboschi