Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@

from livekit.agents import llm

from .utils import convert_mid_conversation_instructions, group_tool_calls
from .utils import (
convert_mid_conversation_instructions,
group_tool_calls,
parse_tool_call_arguments,
)


@dataclass
Expand Down Expand Up @@ -65,7 +69,7 @@ def to_chat_ctx(
"id": msg.call_id,
"type": "tool_use",
"name": msg.name,
"input": json.loads(msg.arguments or "{}"),
"input": parse_tool_call_arguments(msg),
}
)
elif msg.type == "function_call_output":
Expand Down
9 changes: 6 additions & 3 deletions livekit-agents/livekit/agents/llm/_provider_format/aws.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from __future__ import annotations

import itertools
import json
from dataclasses import dataclass
from typing import Any

from livekit.agents import llm

from .utils import convert_mid_conversation_instructions, group_tool_calls
from .utils import (
convert_mid_conversation_instructions,
group_tool_calls,
parse_tool_call_arguments,
)

_AWS_IMAGE_FORMATS = {
"image/jpeg": "jpeg",
Expand Down Expand Up @@ -66,7 +69,7 @@ def to_chat_ctx(
"toolUse": {
"toolUseId": msg.call_id,
"name": msg.name,
"input": json.loads(msg.arguments or "{}"),
"input": parse_tool_call_arguments(msg),
}
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
from livekit.agents import llm
from livekit.agents.log import logger

from .utils import convert_mid_conversation_instructions, group_tool_calls
from .utils import (
convert_mid_conversation_instructions,
group_tool_calls,
parse_tool_call_arguments,
)


@dataclass
Expand Down Expand Up @@ -65,7 +69,7 @@ def to_chat_ctx(
"function_call": {
"id": msg.call_id,
"name": msg.name,
"args": json.loads(msg.arguments or "{}"),
"args": parse_tool_call_arguments(msg),
}
}
# Inject thought_signature if available (Gemini 3 multi-turn function calling)
Expand Down
37 changes: 37 additions & 0 deletions livekit-agents/livekit/agents/llm/_provider_format/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,50 @@

from collections import OrderedDict
from dataclasses import dataclass, field
from typing import Any

from livekit.agents import llm
from livekit.agents.log import logger

_DEFAULT_INLINE_INSTRUCTIONS_TEMPLATE = "<instructions>\n{content}\n</instructions>"


def parse_tool_call_arguments(fnc_call: llm.FunctionCall) -> dict[str, Any]:
"""Parse a stored function call's arguments into a dict for JSON-object providers.

``FunctionCall.arguments`` is only canonicalized when the model's output was
parsed at the time of the call; when it can't be recovered the raw string is kept
verbatim, and history restored via ``ChatContext.from_dict`` or produced by a
custom ``llm_node`` never went through that path at all. The Anthropic, Google,
and AWS formatters send the arguments as a JSON object, so formatting such history
would otherwise raise on an unrelated later turn -- and because the bad entry
stays in the context, every subsequent turn raises again.

:func:`~livekit.agents.llm.utils.parse_function_arguments` does the recovery
(strict parse, then ``json_repair``, then chat-template token stripping, then
unwrapping double-encoded arguments). It raises ``ValueError`` when it cannot
reach a dict, which is the right contract for a live call the model can retry,
but not for replaying history: fall back to an empty object rather than
fabricating arguments the model never sent, since the historical call already
produced its output.
"""
# imported here rather than at module scope: ``llm.utils`` imports
# ``chat_context``, which imports this package, so a top-level import is a cycle
from ..utils import parse_function_arguments

arguments = fnc_call.arguments
if not arguments:
return {}
try:
return parse_function_arguments(arguments)
except ValueError:
logger.warning(
"could not parse stored tool call arguments as a JSON object, using empty arguments",
extra={"call_id": fnc_call.call_id, "tool_name": fnc_call.name},
)
return {}


def convert_mid_conversation_instructions(
chat_ctx: llm.ChatContext,
*,
Expand Down
93 changes: 93 additions & 0 deletions tests/test_chat_ctx.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,3 +782,96 @@ def test_upsert_still_replaces_an_item_in_place():

assert [item.id for item in ctx.items] == ["a", "b"]
assert ctx.items[0].text_content == "first, corrected"


# formats that send tool call arguments as a JSON object (vs. an opaque string like openai/mistral)
_JSON_OBJECT_FORMATS = ["anthropic", "google", "aws"]


def _tool_call_input(fmt: str, messages: list[dict[str, Any]]) -> Any:
"""Pull the single tool call's arguments out of a provider-formatted context."""
if fmt == "google":
for turn in messages:
for part in turn["parts"]:
if "function_call" in part:
return part["function_call"]["args"]
elif fmt == "anthropic":
for msg in messages:
for block in msg["content"]:
if isinstance(block, dict) and block.get("type") == "tool_use":
return block["input"]
elif fmt == "aws":
for msg in messages:
for block in msg["content"]:
if isinstance(block, dict) and "toolUse" in block:
return block["toolUse"]["input"]
raise AssertionError(f"no tool call found in {fmt} messages")


@pytest.mark.parametrize("fmt", _JSON_OBJECT_FORMATS)
def test_to_provider_format_tolerates_unparseable_tool_arguments(fmt: str):
"""A stored tool call whose arguments never parsed must not crash a later turn.

`FunctionCall.arguments` is kept verbatim when it can't be parsed (unrecoverable
open-weight output, or history restored via `ChatContext.from_dict`). The
Anthropic/Google/AWS formatters send arguments as a JSON object, so formatting
such history previously raised `json.JSONDecodeError`. It should degrade to an
empty object instead.
"""
ctx = ChatContext.empty()
ctx.insert(FunctionCall(call_id="c1", name="lookup", arguments="not-a-json-object"))
ctx.insert(FunctionCallOutput(call_id="c1", name="lookup", output="tool error", is_error=True))

messages, _ = ctx.to_provider_format(format=fmt)
assert _tool_call_input(fmt, messages) == {}


@pytest.mark.parametrize("fmt", _JSON_OBJECT_FORMATS)
def test_to_provider_format_preserves_valid_tool_arguments(fmt: str):
"""Valid JSON-object arguments are still passed through unchanged."""
ctx = ChatContext.empty()
ctx.insert(FunctionCall(call_id="c1", name="lookup", arguments='{"order": "123"}'))
ctx.insert(FunctionCallOutput(call_id="c1", name="lookup", output="ok", is_error=False))

messages, _ = ctx.to_provider_format(format=fmt)
assert _tool_call_input(fmt, messages) == {"order": "123"}


@pytest.mark.parametrize("fmt", _JSON_OBJECT_FORMATS)
@pytest.mark.parametrize(
("arguments", "expected"),
[
('{"a": 1,}', {"a": 1}),
('{"a": <|end|>1}', {"a": "end1"}),
('"{\\"a\\": 1}"', {"a": 1}),
],
ids=["trailing-comma", "chat-template-leak", "double-encoded"],
)
def test_to_provider_format_recovers_repairable_tool_arguments(
fmt: str, arguments: str, expected: dict[str, Any]
):
"""Recoverable arguments are repaired rather than discarded.

Routing through `llm.utils.parse_function_arguments` means json_repair, chat-template
token stripping and double-encoded unwrapping all apply here too, so history that a
bare `json.loads` would have dropped to `{}` keeps its real arguments.
"""
ctx = ChatContext.empty()
ctx.insert(FunctionCall(call_id="c1", name="lookup", arguments=arguments))
ctx.insert(FunctionCallOutput(call_id="c1", name="lookup", output="ok", is_error=False))

messages, _ = ctx.to_provider_format(format=fmt)
assert _tool_call_input(fmt, messages) == expected


@pytest.mark.parametrize("fmt", _JSON_OBJECT_FORMATS)
@pytest.mark.parametrize("arguments", ["", "[1, 2, 3]", "42", "null"])
def test_to_provider_format_non_object_tool_arguments(fmt: str, arguments: str):
"""Empty or non-object arguments degrade to `{}`; a call's arguments are always a
named-parameter object, so an array/scalar/null is treated as no arguments."""
ctx = ChatContext.empty()
ctx.insert(FunctionCall(call_id="c1", name="lookup", arguments=arguments))
ctx.insert(FunctionCallOutput(call_id="c1", name="lookup", output="ok", is_error=False))

messages, _ = ctx.to_provider_format(format=fmt)
assert _tool_call_input(fmt, messages) == {}