Compare commits

..
Author SHA1 Message Date
Josh Hawkins 16784d055c normalize whitespace in custom export ffmpeg args
The custom export validator tokenized args on any whitespace, but the export command was built by splitting on single spaces, so repeated spaces, tabs, or newlines produced a different argv than the one that was validated. The exporter now rejoins custom args with single spaces so ffmpeg receives exactly the tokens the validator checked.
2026-11-23 09:38:33 -06:00
6 changed files with 47 additions and 84 deletions
+2 -14
View File
@@ -6,7 +6,6 @@ import json
import logging
import operator
import time
import uuid
from datetime import datetime
from functools import reduce
from typing import Any, Literal
@@ -1275,14 +1274,6 @@ def _pending_tool_calls_from_tail(
return parse_tool_calls_from_message(tail)
def _with_server_ids(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Give each model tool call a unique id.
Approvals are keyed by id, and some providers reuse ids across calls.
"""
return [{**tc, "id": uuid.uuid4().hex[:9]} for tc in tool_calls]
def _tool_calls_awaiting_approval(
pending_tool_calls: list[dict[str, Any]],
body: ChatCompletionRequest,
@@ -1608,7 +1599,6 @@ async def chat_completion(
return
requested = msg.get("tool_calls")
if requested:
requested = _with_server_ids(requested)
stream_iterations += 1
conversation.append(
build_assistant_message_for_conversation(
@@ -1694,15 +1684,13 @@ async def chat_completion(
status_code=500,
)
pending_tool_calls = response.get("tool_calls")
if pending_tool_calls:
pending_tool_calls = _with_server_ids(pending_tool_calls)
conversation.append(
build_assistant_message_for_conversation(
response.get("content"), pending_tool_calls
response.get("content"), response.get("tool_calls")
)
)
pending_tool_calls = response.get("tool_calls")
if not pending_tool_calls:
logger.debug(
f"Chat completion finished with final answer (iterations: {tool_iterations})"
-15
View File
@@ -67,17 +67,6 @@ def _decode_data_uri(url: str) -> tuple[str, bytes] | None:
return None
def _tool_names_by_id(messages: list[dict[str, Any]]) -> dict[str, str]:
"""Map each assistant tool call id to its function name."""
return {
tc["id"]: (tc.get("function") or {}).get("name") or ""
for msg in messages
if msg.get("role") == "assistant"
for tc in msg.get("tool_calls") or []
if tc.get("id")
}
def _parts_from_content(content: Any) -> list[types.Part]:
"""Convert OpenAI-style message content (str or multimodal list) to Gemini parts."""
if isinstance(content, list):
@@ -469,7 +458,6 @@ class GeminiClient(GenAIClient):
try:
# Convert messages to Gemini format
gemini_messages: list[types.Content] = []
tool_names = _tool_names_by_id(messages)
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
@@ -532,7 +520,6 @@ class GeminiClient(GenAIClient):
parts=[
types.Part.from_function_response(
name=msg.get("name")
or tool_names.get(msg.get("tool_call_id") or "")
or msg.get("tool_call_id")
or "",
response=response_payload,
@@ -727,7 +714,6 @@ class GeminiClient(GenAIClient):
try:
# Convert messages to Gemini format
gemini_messages: list[types.Content] = []
tool_names = _tool_names_by_id(messages)
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
@@ -790,7 +776,6 @@ class GeminiClient(GenAIClient):
parts=[
types.Part.from_function_response(
name=msg.get("name")
or tool_names.get(msg.get("tool_call_id") or "")
or msg.get("tool_call_id")
or "",
response=response_payload,
+14 -2
View File
@@ -261,6 +261,18 @@ def validate_ffmpeg_args(args: str) -> tuple[bool, str]:
return True, ""
def normalize_ffmpeg_args(args: str | None) -> str | None:
"""Rejoin args with single spaces.
validate_ffmpeg_args tokenizes on any whitespace, while export commands are
built with split(" "). Normalizing keeps the two token lists identical.
"""
if args is None:
return None
return " ".join(args.split())
class PlaybackSourceEnum(str, Enum):
recordings = "recordings"
preview = "preview"
@@ -327,8 +339,8 @@ class RecordingExporter(threading.Thread):
self.end_time = end_time
self.playback_source = playback_source
self.export_case_id = export_case_id
self.ffmpeg_input_args = ffmpeg_input_args
self.ffmpeg_output_args = ffmpeg_output_args
self.ffmpeg_input_args = normalize_ffmpeg_args(ffmpeg_input_args)
self.ffmpeg_output_args = normalize_ffmpeg_args(ffmpeg_output_args)
self.cpu_fallback = cpu_fallback
self.chapters = chapters
self.stream = stream
-17
View File
@@ -22,7 +22,6 @@ from frigate.api.chat import (
_execute_pending_tools,
_pending_tool_calls_from_tail,
_tool_calls_awaiting_approval,
_with_server_ids,
)
from frigate.api.defs.request.chat_body import ChatCompletionRequest
from frigate.genai.prompts import (
@@ -153,22 +152,6 @@ class TestApprovalHelpers(unittest.TestCase):
body = _body(tool_decisions={"c2": "approve", "c3": "reject"})
self.assertEqual(_tool_calls_awaiting_approval(pending, body, WRITE_TOOLS), [])
def test_repeated_provider_ids_get_unique_server_ids(self):
calls = [
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
]
renamed = _with_server_ids(calls)
self.assertEqual(len({tc["id"] for tc in renamed}), 2)
self.assertNotIn("set_camera_state", {tc["id"] for tc in renamed})
# A later call to the same tool is not covered by an earlier decision.
body = _body(tool_decisions={renamed[0]["id"]: "approve"})
later = _with_server_ids(calls[:1])
self.assertEqual(
len(_tool_calls_awaiting_approval(later, body, WRITE_TOOLS)), 1
)
class TestExecutePendingTools(unittest.TestCase):
def test_rejected_call_is_not_executed(self):
+31
View File
@@ -143,6 +143,37 @@ class TestValidateFfmpegArgs(unittest.TestCase):
self.assertRejected("-metadata comment=x")
class TestCustomArgsTokenization(unittest.TestCase):
"""The built command must contain exactly the tokens the validator checked."""
def test_irregular_whitespace_does_not_shift_tokens(self) -> None:
output_args = "-c:v libx264\t-crf 23\n -r 25 "
self.assertTrue(validate_ffmpeg_args(output_args)[0])
with patch("frigate.record.export.Path.mkdir"):
exporter = RecordingExporter(
MagicMock(),
"front_abc123",
"front",
None,
None,
1_000,
2_000,
PlaybackSourceEnum.recordings,
ffmpeg_input_args=" -an ",
ffmpeg_output_args=output_args,
)
exporter.config.ffmpeg.ffmpeg_path = "ffmpeg"
exporter.staged_runs = ["/cache/stage_0.mp4"]
cmd, _ = exporter.get_record_export_command("/exports/out.mp4")
for token in cmd[: cmd.index("-metadata")]:
self.assertNotEqual(token, "")
self.assertEqual(token.split(), [token])
self.assertIn("-c:v libx264 -crf 23 -r 25", " ".join(cmd))
class TestExportVideoPath(unittest.TestCase):
"""Tests for the file path an export takes once the user names it."""
-36
View File
@@ -500,42 +500,6 @@ class TestGeminiProvider(unittest.TestCase):
final = _final_message(_collect(client, MULTIMODAL_MESSAGES))
self.assertEqual(final["content"], "ok")
def test_tool_response_name_resolves_from_call_id(self):
from google.genai.types import FinishReason
client = self._client()
self._patch_stream(
client,
[
_gemini_chunk(
parts=[_gemini_part(text="ok")], finish_reason=FinishReason.STOP
)
],
)
messages = [
{"role": "user", "content": "turn off recordings"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_abc",
"type": "function",
"function": {"name": "set_camera_state", "arguments": "{}"},
}
],
},
{"role": "tool", "tool_call_id": "call_abc", "content": "{}"},
]
_collect(client, messages)
contents = client.provider.aio.models.generate_content_stream.call_args.kwargs[
"contents"
]
self.assertEqual(
contents[-1].parts[0].function_response.name, "set_camera_state"
)
class TestGeminiImageTokens(unittest.TestCase):
def _client(self, count_tokens):