fix(ai): send OpenAI-compatible tool payloads that strict endpoints accept

Merged
YA
2mo ago
+145-7

Fixes #3726

Summary

Chat turns that involve tool calling always fail with 400 on strict OpenAI-compatible providers (GLM/Z.ai-backed endpoints tested via OPENAI_URI_BASE + OPENAI_SUPPORTS_RESPONSES_ENDPOINT=false). The first round succeeds; the follow-up request that sends tool results back is rejected.

Two payload-conformance bugs cause it:

  1. Tool result messages include the deprecated name field. Upstream error captured from the provider:

    messages[5]: "name" is not supported by this endpoint

    Dropped from both places that build tool messages:

    • Provider::Openai#build_generic_messages (the follow-up request)
    • Assistant::Responder#openai_messages_payload (conversation history — without this, later turns keep failing)
  2. ToolCall::Function#to_tool_call sent function.arguments as a JSON object (straight from the jsonb column) while the OpenAI schema requires a JSON-encoded string; some endpoints 400 on the object form. Now serialized to a string when it isn't one already. (build_generic_messages already did this for the follow-up assistant message — this fixes the same payload in history/to_tool_call.)

Testing

  • New ToolCall::FunctionTest covering: object → JSON string, string left untouched, to_result unchanged.
  • New Provider::OpenaiTest case stubbing client.chat on the generic (custom-provider) path asserting: tool_calls[*].function.arguments is a String, tool message has no name key, tool_call_id preserved.
  • Verified live against a GLM-backed endpoint: reproduced the 400 with the exact payload (bisected: name → 400, without → 200; object args → 400, string args → 200), applied the patch, chat with tool calls completes normally.

Syntax checked with ruby -c on all touched files.

Summary by CodeRabbit

  • Bug Fixes
    • Tool-result messages no longer include the deprecated name field. Tool-call IDs and result content remain available.
    • Function-call arguments are serialized consistently: object arguments become JSON strings, existing nonblank strings are preserved, and blank or missing arguments are represented as "{}". Tool-call payloads use this format, while tool results continue to preserve object arguments.