mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-23 22:07:07 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69b6bd3544 | ||
|
|
0ff8718057 |
+14
-2
@@ -6,6 +6,7 @@ import json
|
||||
import logging
|
||||
import operator
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from functools import reduce
|
||||
from typing import Any, Literal
|
||||
@@ -1274,6 +1275,14 @@ 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,
|
||||
@@ -1599,6 +1608,7 @@ 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(
|
||||
@@ -1684,13 +1694,15 @@ 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"), response.get("tool_calls")
|
||||
response.get("content"), pending_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})"
|
||||
|
||||
@@ -67,6 +67,17 @@ 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):
|
||||
@@ -458,6 +469,7 @@ 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", "")
|
||||
@@ -520,6 +532,7 @@ 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,
|
||||
@@ -714,6 +727,7 @@ 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", "")
|
||||
@@ -776,6 +790,7 @@ 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,
|
||||
|
||||
@@ -261,18 +261,6 @@ 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"
|
||||
@@ -339,8 +327,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 = normalize_ffmpeg_args(ffmpeg_input_args)
|
||||
self.ffmpeg_output_args = normalize_ffmpeg_args(ffmpeg_output_args)
|
||||
self.ffmpeg_input_args = ffmpeg_input_args
|
||||
self.ffmpeg_output_args = ffmpeg_output_args
|
||||
self.cpu_fallback = cpu_fallback
|
||||
self.chapters = chapters
|
||||
self.stream = stream
|
||||
|
||||
@@ -22,6 +22,7 @@ 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 (
|
||||
@@ -152,6 +153,22 @@ 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):
|
||||
|
||||
@@ -143,37 +143,6 @@ 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."""
|
||||
|
||||
|
||||
@@ -500,6 +500,42 @@ 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):
|
||||
|
||||
Reference in New Issue
Block a user