fix(completion): keep the assistant fill for a role-less function_call turn

This commit is contained in:
mateo-berri 2026-10-29 18:26:54 -07:00
parent b940de5a13
commit d0adb59a8a
2 changed files with 18 additions and 6 deletions

View file

@ -9127,14 +9127,15 @@ def validate_and_fix_openai_messages(
"""
Ensures all messages are valid OpenAI chat completion messages.
Only an assistant turn carries tool_calls, so one sent without a role gets "assistant" (issue #8661).
Only an assistant turn carries tool_calls or function_call, so one sent without a role gets "assistant"
(issue #8661).
"""
new_messages: Final = []
for message in messages:
if message.get("tool_calls"):
message["tool_calls"] = jsonify_tools(tools=message["tool_calls"])
if not message.get("role"):
message["role"] = "assistant"
if not message.get("role") and (message.get("tool_calls") or message.get("function_call")):
message["role"] = "assistant"
convert_msg_to_dict = cast( # cast-ok: message dicts satisfy the TypedDict shape
AllMessageValues,

View file

@ -8291,10 +8291,21 @@ def test_completion_message_without_role_is_a_400(messages: list[dict[str, str |
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
def test_completion_role_less_tool_call_turn_is_sent_as_assistant():
@pytest.mark.parametrize(
"call_turn",
[
{
"content": "",
"tool_calls": [
{"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}
],
},
{"content": None, "function_call": {"name": "get_weather", "arguments": "{}"}},
],
)
def test_completion_role_less_tool_call_turn_is_sent_as_assistant(call_turn: dict[str, object]):
"""Only an assistant turn carries tool calls, so one replayed without a role still goes upstream as assistant."""
tool_call: Final = {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}
messages: Final = [{"role": "user", "content": "Weather in Paris?"}, {"content": "", "tool_calls": [tool_call]}]
messages: Final = [{"role": "user", "content": "Weather in Paris?"}, call_turn]
assert validate_and_fix_openai_messages(messages)[1]["role"] == "assistant"