Skip to content

Multi-turn tool calling is broken for OpenAI-compatible backends #1349

Closed

Description

@0ndrec

Summary

When building a multi-turn agent loop using start_session + repeated instruct calls with tool_calls=True, the second turn crashes (or silently produces wrong results) due to two related bugs in how mellea serializes the conversation history for OpenAI-compatible providers:

  1. ChatFormatter discards tool call metadata, producing an assistant message with content: "" and no tool_calls array — which providers like Cohere reject with 400 invalid message: must have non-empty content or tool calls.
  2. extract_model_tool_requests crashes on truncated JSON, raising an uncaught json.JSONDecodeError that kills the whole agent when a model streams a malformed argument string.

These two bugs together make multi-turn tool use unreliable with the OpenAI backend.


Bug 1 — ChatFormatter.to_chat_messages loses tool call data from assistant messages

Description

When the model responds with only a tool call (no accompanying text), ModelOutputThunk.value is an empty string "". On the next turn, ChatFormatter.to_chat_messages serializes this thunk's parsed_repr into a Message whose content is the Python str() of the raw tool_calls list — a representation like "[{'id': 'call_abc', 'function': ...}]". That string is then passed through message_to_openai_message, which produces:

{"role": "assistant", "content": "[{'id': 'call_abc', ...}]"}

This is wrong in two ways:

  • The tool_calls array is absent — providers that enforce the OpenAI spec require it.
  • The content value is a Python repr, not null/"" as the spec expects for tool-only turns.

The OpenAI spec for an assistant turn that calls a tool is:

{
  "role": "assistant",
  "content": null,
  "tool_calls": [
    {
      "id": "call_abc123",
      "type": "function",
      "function": {
        "name": "list_dir",
        "arguments": "{\"path\": \".\"}"
      }
    }
  ]
}

Affected files

File Relevant code
mellea/formatters/chat_formatter.py ChatFormatter.to_chat_messages — line 55–63, parsed_repr branch
mellea/stdlib/components/chat.py Message._parse — lines 132–143, OpenAI branch
mellea/helpers/openai_compatible_helpers.py message_to_openai_message — line 208, only emits role+content

Root cause trace

chat_formatter.py lines 55–63:

if c.parsed_repr is not None:
    if isinstance(c.parsed_repr, Component):
        c = c.parsed_repr   # ← becomes the Message below

chat.py Message._parse lines 132–143 (called to set parsed_repr):

elif "oai_chat_response" in computed._meta:
    return Message(
        role=computed._meta["oai_chat_response"]["choices"][0]["message"]["role"],
        content=str(                                       # ← Python repr, not null
            computed._meta["oai_chat_response"]["choices"][0]["message"]
            .get("tool_calls", [])
        ),
    )

openai_compatible_helpers.py message_to_openai_message line 208:

return {"role": msg.role, "content": content}   # ← no tool_calls key ever emitted

Error observed

openai.BadRequestError: Error code: 400 - {
  "error": {
    "message": "Provider returned error",
    "metadata": {
      "raw": "invalid request: invalid message provided at index 1:
              must have non-empty content or tool calls."
    }
  }
}

Expected behaviour

On multi-turn calls, the assistant message in the serialized history should include the tool_calls array in proper OpenAI format, with content set to null (or omitted). Tool result messages that are fed back should use role: "tool" with a matching tool_call_id.

Proposed fix

message_to_openai_message should emit tool_calls when the source ModelOutputThunk carried them. The simplest approach is to thread the raw oai_chat_response choice through to the serialization step and use it directly rather than going through Message._parse → str() → re-serialize:

def message_to_openai_message(msg: Message, formatter=None, raw_tool_calls=None) -> dict:
    content = formatter.print(msg) if formatter else msg.content
    result = {"role": msg.role, "content": content or None}
    if raw_tool_calls:
        result["tool_calls"] = raw_tool_calls
        result["content"] = None   # spec: null when tool_calls present
    return result

Alternatively, ChatFormatter.to_chat_messages could attach the raw oai_chat_response choice dict to the Message it returns for ModelOutputThunk assistant turns, letting message_to_openai_message pass it through verbatim.


Bug 2 — extract_model_tool_requests crashes on truncated JSON arguments

Description

Some models (particularly smaller/free-tier models) occasionally return truncated or malformed JSON strings in tool call arguments when streaming. extract_model_tool_requests calls json.loads(tool_args) with no error handling, which raises an uncaught json.JSONDecodeError that propagates all the way up through astream → post_processing and kills the entire agent.

Affected file

mellea/helpers/openai_compatible_helpers.py, line 74 (before fix):

args = {}
if tool_args is not None:
    # Returns the args as a string. Parse it here.
    args = json.loads(tool_args)          # ← raises JSONDecodeError on bad input

Error observed

  File "mellea/helpers/openai_compatible_helpers.py", line 74, in extract_model_tool_requests
    args = json.loads(tool_args)
json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 50 (char 49)

Full traceback root in agent code:

  File "loop.py", line 70, in agent_loop
    result = m.instruct(prompt, ..., tool_calls=True)
  ...
  File "mellea/backends/openai.py", line 1082, in post_processing
    tool_chunk = extract_model_tool_requests(tools, choice_response)
  File "mellea/helpers/openai_compatible_helpers.py", line 74
    args = json.loads(tool_args)
json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 50 (char 49)

Expected behaviour

A malformed argument string should be logged as a warning and the specific tool call should be skipped, not crash the process. The agent can then re-prompt or handle the gap gracefully.

Proposed fix

Wrap the json.loads call:

args = {}
if tool_args is not None:
    try:
        args = json.loads(tool_args)
    except json.JSONDecodeError:
        MelleaLogger.get_logger().warning(
            f"Tool '{tool_name}' returned malformed JSON arguments "
            f"(likely truncated during streaming): {tool_args!r} — skipping call"
        )
        continue

This is a minimal, safe fix: bad tool calls are dropped rather than crashing. A more advanced approach could attempt JSON repair (e.g. closing an unterminated string) before falling back to skip.


Reproduction

Minimal agent loop (Python 3.13, mellea 0.6.0, OpenRouter / any streaming OpenAI-compatible backend):

from mellea import start_session
from mellea.backends import ModelOption, tools

@tools.tool
def list_dir(path: str = ".") -> str:
    """List directory contents. Args: path: directory path."""
    import os
    return "\n".join(os.listdir(path))

m = start_session(
    "openai",
    model_id="cohere/north-mini-code:free",   # or any model that calls tools
    context_type="chat",
    base_url="https://openrouter.ai/api/v1",
    api_key="<OPENROUTER_API_KEY>",
    model_options={
        ModelOption.SYSTEM_PROMPT: "You are a coding agent. Use tools to answer.",
        ModelOption.TEMPERATURE: 0.1,
        ModelOption.MAX_NEW_TOKENS: 512,
    },
)

# Turn 1 — model calls list_dir, no text content → succeeds
result = m.instruct("list the files here", model_options={ModelOption.TOOLS: [list_dir]}, tool_calls=True)
print("tool_calls:", result.tool_calls)   # {'list_dir': ModelToolCall(...)}

# Execute tool and feed result back
output = str(result.tool_calls["list_dir"].call_func())

# Turn 2 — crashes with BadRequestError (Bug 1) or JSONDecodeError (Bug 2)
result2 = m.instruct(
    f'<tool_result tool="list_dir">{output}</tool_result>',
    model_options={ModelOption.TOOLS: [list_dir]},
    tool_calls=True,
)

Bug 1 triggers on turn 2 with Cohere/OpenRouter (and any provider that validates the tool_calls array).
Bug 2 triggers on turn 1 or 2 whenever the model streams a truncated argument string (non-deterministic but reproducible with free-tier small models).


Workarounds (applied in downstream project pending upstream fix)

Bug 1 — Use a fresh start_session per turn and inject accumulated tool history as plain text in the next prompt (stateless scratchpad pattern). This avoids the broken multi-turn serialization.

Bug 2 — Patch extract_model_tool_requests locally (see proposed fix above). Note this patch is lost on uv sync.


Environment

mellea:    0.6.0
Python:    3.13 (CPython, Windows x86-64)
openai:    (SDK used internally by mellea)
Provider:  OpenRouter — cohere/north-mini-code:free
OS:        Windows 11 Pro 10.0.26200

Activity

  1. added
    bug
    area/tools
    on Jun 26, 2026
  2. psschwei commented on Jun 26, 2026

    @psschwei
    Contributor

    cc @AngeloDanducci @akihikokuroda (I think this may touch the area(s) one or both of you were recently working on?)

  3. mvanhorn commented on Jul 8, 2026

    @mvanhorn
    Contributor

    Opened #1373 for both bugs: Message now carries tool_calls through history serialization (emitted with content: null for tool-only turns), and extract_model_tool_requests skips-with-warning on malformed/truncated tool-arg JSON instead of raising. Scoped to the two you reported; the role: 'tool' feedback half is noted as a follow-up. Added regression tests for both.

  4. added a commit that references this issue on Jul 13, 2026
    9b2f528
  5. added a commit that references this issue on Jul 14, 2026
    4c80e10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/toolsbug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions