Responses LLM executes a function call that was cut off by max_output_tokens, with JSON-repaired truncated arguments
Bug Description
With the Responses engine (openai.responses.LLM, and inference.responses.LLM which shares it), a function_call item that the model did not finish is still sent to the tool executor.
When a response runs out of output tokens while the model is writing tool arguments, the server closes the item with response.output_item.done and item.status == "incomplete", then ends the stream with response.incomplete (reason: max_output_tokens). _handle_output_items_done only checks item.type == "function_call", so it emits the call immediately. response.incomplete does raise APIStatusError one event later, but by then voice/generation.py has already put the call on function_ch, and the tool executor consumes that channel concurrently. The error cannot take the call back.
parse_function_arguments then falls back to json_repair, so a truncated {"temperature": 2 (the model was writing 21) becomes a valid {"temperature": 2}. The tool runs with the wrong value, and the call and its successful output are written to session.history:
repaired malformed function-call JSON arguments
run() raised: APIStatusError('response incomplete: max_output_tokens', status_code=-1, request_id=None, body=None, retryable=False)
executed: [2]
history: function_call {"temperature": 2}
history: function_call_output 'Temperature set to 2' is_error = False
The same thing happened in the GPT Live backend and was fixed there in #7230, which requires status == "completed" before dispatching. That PR only touched realtime/gpt_live_model.py; the shared Responses engine still has the gap.
Expected Behavior
A function call whose item status is incomplete (or in_progress) should not be emitted as a tool call. The stream should still fail with the existing APIStatusError("response incomplete: max_output_tokens"), and the tool should not run or appear in the history.
Reproduction Steps
# Fully offline: an httpx MockTransport returns the SSE events, everything else is the
# real openai SDK, openai.responses.LLM and AgentSession.
# Save as repro.py and run: python repro.py
import asyncio
import json
import httpx2 as httpx # the HTTP client package the openai SDK depends on
import openai
from livekit.agents import Agent, AgentSession, function_tool
from livekit.plugins.openai.responses import LLM
RESPONSE = {"id": "resp_1", "created_at": 0, "model": "gpt-4.1", "object": "response",
"output": [], "parallel_tool_calls": False, "tool_choice": "auto", "tools": []}
# The model ran out of output tokens while writing {"temperature": 21}
CALL = {"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "set_temperature",
"arguments": '{"temperature": 2', "status": "incomplete"}
TRUNCATED = [
{"type": "response.created", "sequence_number": 0,
"response": {**RESPONSE, "status": "in_progress"}},
{"type": "response.output_item.done", "sequence_number": 1, "output_index": 0, "item": CALL},
{"type": "response.incomplete", "sequence_number": 2,
"response": {**RESPONSE, "status": "incomplete", "output": [CALL],
"incomplete_details": {"reason": "max_output_tokens"}}},
]
DONE = [
{"type": "response.created", "sequence_number": 0,
"response": {**RESPONSE, "status": "in_progress"}},
{"type": "response.completed", "sequence_number": 1,
"response": {**RESPONSE, "status": "completed"}},
]
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "GET": # model-list prewarm
return httpx.Response(200, json={"object": "list", "data": []})
events = TRUNCATED if handler.calls == 0 else DONE
handler.calls += 1
body = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in events)
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
handler.calls = 0
executed: list[int] = []
@function_tool
async def set_temperature(temperature: int) -> str:
"""Set the room temperature."""
executed.append(temperature)
return f"Temperature set to {temperature}"
async def main() -> None:
http_client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
client = openai.AsyncOpenAI(api_key="unused", base_url="https://offline.invalid/v1",
http_client=http_client)
model = LLM(model="gpt-4.1", client=client) # a custom client uses the HTTP transport
async with AgentSession(llm=model) as session:
await session.start(Agent(instructions="Set the temperature.", tools=[set_temperature]))
try:
await session.run(user_input="Set it to 21 degrees.")
except Exception as e:
print("run() raised:", repr(e))
print("executed:", executed)
for item in session.history.items:
if item.type == "function_call":
print("history:", item.type, item.arguments)
elif item.type == "function_call_output":
print("history:", item.type, repr(item.output), "is_error =", item.is_error)
await model.aclose()
asyncio.run(main())
# Output on main (8dc939027):
# executed: [2]
# history: function_call {"temperature": 2}
# history: function_call_output 'Temperature set to 2' is_error = False
# Expected: executed: [] and no function_call / function_call_output in the history.
# The WebSocket transport goes through the same _process_event and behaves the same way.
Operating System
macOS 26.6 (arm64)
Models Used
No response
Package Versions
livekit-agents: main @ 8dc9390276a8d50ea10eec8cf7a7e836cac30f65 (1.8.13)
livekit-plugins-openai: same checkout
livekit==1.2.1
openai==3.51.0
json-repair==0.63.5
Python 3.12.16
Session/Room/Call IDs
No response
Proposed Solution
# In ResponsesLLMStream._handle_output_items_done, skip a function call whose status is set
# and is not "completed" (same rule as #7230 for GPT Live). Items without a status, which
# some Responses-compatible providers send, keep today's behavior. response.incomplete
# still raises, so the caller still sees why the turn failed.
if event.item.type == "function_call":
if event.item.status not in (None, "completed"):
logger.debug(
"ignoring function call that did not complete",
extra={"function": event.item.name, "status": event.item.status},
)
return None
...
Additional Context
Relevant code on main:
_handle_output_items_donebuilds aFunctionToolCallwithout looking atitem.status._process_eventsends that chunk right away;response.incompleteraises only on the following event (_handle_response_incomplete).voice/generation.pyforwards each tool call tofunction_chas soon as its chunk arrives.parse_function_argumentsrepairs the truncated JSON into something callable.
The engine does not handle response.function_call_arguments.delta, so output_item.done is the only place tool calls are emitted; response.incomplete and response.failed only raise and never emit the items in their output.
Related: #7230 (same fix for GPT Live), #7013 / #7024 (response.incomplete handling on the WebSocket transport).
I'm happy to send a PR with the fix and regression tests.
AI disclosure: I used an AI assistant to help investigate this and draft the report. I ran the reproduction myself and checked the output.
Screenshots and Recordings
No response