mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-23 22:07:07 +03:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69b6bd3544 | ||
|
|
0ff8718057 | ||
|
|
3bca9b8676 |
@@ -22,3 +22,6 @@ add_header Set-Cookie $auth_cookie;
|
||||
## Pass the location header back up if it exists
|
||||
auth_request_set $redirection_url $upstream_http_location;
|
||||
add_header Location $redirection_url;
|
||||
|
||||
## The add_header lines above stop this location inheriting server-level headers
|
||||
include security_headers.conf;
|
||||
|
||||
@@ -152,7 +152,6 @@ http {
|
||||
sub_filter '.m4s' '.m4s$is_args$args';
|
||||
sub_filter '.mp4"' '.mp4$is_args$args"';
|
||||
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "no-store";
|
||||
expires off;
|
||||
|
||||
@@ -161,7 +160,6 @@ http {
|
||||
|
||||
location /stream/ {
|
||||
include auth_request.conf;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "no-store";
|
||||
expires off;
|
||||
|
||||
@@ -185,7 +183,6 @@ http {
|
||||
}
|
||||
|
||||
expires 7d;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "public";
|
||||
autoindex on;
|
||||
root /media/frigate;
|
||||
@@ -226,7 +223,7 @@ http {
|
||||
|
||||
location /ws {
|
||||
include auth_request.conf;
|
||||
proxy_pass http://mqtt_ws/;
|
||||
proxy_pass http://mqtt_ws;
|
||||
include proxy.conf;
|
||||
}
|
||||
|
||||
@@ -290,7 +287,6 @@ http {
|
||||
|
||||
location /api/ {
|
||||
include auth_request.conf;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "no-store";
|
||||
expires off;
|
||||
proxy_pass http://frigate_api/;
|
||||
|
||||
+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})"
|
||||
|
||||
@@ -581,6 +581,7 @@ class WebPushClient(Communicator):
|
||||
sorted_objects.add(obj)
|
||||
|
||||
sorted_objects.update(payload["after"]["data"]["sub_labels"])
|
||||
sorted_objects.update(payload["after"]["data"]["audio"])
|
||||
|
||||
image = f"{payload['after']['thumb_path'].replace(BASE_DIR, '')}"
|
||||
ended = state == "end" or state == "genai"
|
||||
@@ -617,7 +618,14 @@ class WebPushClient(Communicator):
|
||||
else:
|
||||
formatted_zone_names.append(titlecase(zone_name.replace("_", " ")))
|
||||
|
||||
title = f"{titlecase(', '.join(sorted_objects).replace('_', ' '))}{' was' if state == 'end' else ''} detected in {', '.join(formatted_zone_names)}"
|
||||
object_names = titlecase(
|
||||
", ".join(sorted(sorted_objects)).replace("_", " ")
|
||||
)
|
||||
title = f"{object_names}{' was' if state == 'end' else ''} detected"
|
||||
|
||||
if formatted_zone_names:
|
||||
title += f" in {', '.join(formatted_zone_names)}"
|
||||
|
||||
message = f"Detected on {camera_name}"
|
||||
|
||||
if ended:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -379,7 +379,7 @@ def move_preview_frames(loc: str) -> None:
|
||||
src,
|
||||
dst,
|
||||
)
|
||||
except shutil.Error:
|
||||
except OSError:
|
||||
logger.error(
|
||||
"Failed to move preview restart cache from %s to %s",
|
||||
src,
|
||||
|
||||
@@ -4,6 +4,7 @@ from unittest.mock import Mock, patch
|
||||
|
||||
import frigate.genai
|
||||
from frigate.config import GenAIProviderEnum
|
||||
from frigate.config.config import RuntimeFilterConfig
|
||||
from frigate.const import MODEL_CACHE_DIR, REDACTED_CREDENTIAL_SENTINEL
|
||||
from frigate.genai import GenAIClient
|
||||
from frigate.models import Event, Recordings, ReviewSegment
|
||||
@@ -98,6 +99,32 @@ class TestHttpApp(BaseTestHttp):
|
||||
assert response.status_code == 200
|
||||
assert app.frigate_config.cameras["front_door"].objects.track == ["person"]
|
||||
|
||||
def test_config_set_in_memory_adds_filters_for_new_tracked_labels(self):
|
||||
self.minimal_config["cameras"]["front_door"]["objects"] = {
|
||||
"track": ["person"],
|
||||
}
|
||||
app = super().create_app()
|
||||
app.config_publisher = Mock()
|
||||
|
||||
with AuthTestClient(app) as client:
|
||||
response = client.put(
|
||||
"/config/set",
|
||||
json={
|
||||
"requires_restart": 0,
|
||||
"skip_save": True,
|
||||
"update_topic": "config/cameras/front_door/objects",
|
||||
"config_data": {
|
||||
"cameras": {
|
||||
"front_door": {"objects": {"track": ["person", "cat"]}}
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
filters = app.frigate_config.cameras["front_door"].objects.filters
|
||||
assert isinstance(filters["cat"], RuntimeFilterConfig)
|
||||
|
||||
@patch("frigate.detectors.detector_config.load_labels")
|
||||
def test_config_set_in_memory_rebinds_replay_model_on_scene_change(
|
||||
self, mock_labels
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
from frigate.config import BirdseyeModeEnum, FrigateConfig
|
||||
from frigate.config.camera.profile import CameraProfileConfig
|
||||
from frigate.config.config import RuntimeFilterConfig
|
||||
from frigate.config.profile import ProfileDefinitionConfig
|
||||
from frigate.config.profile_manager import PERSISTENCE_FILE, ProfileManager
|
||||
from frigate.const import MODEL_CACHE_DIR
|
||||
@@ -502,6 +503,16 @@ class TestProfileManager(unittest.TestCase):
|
||||
back = self.config.cameras["back"]
|
||||
assert back.notifications.enabled is True
|
||||
|
||||
@patch.object(ProfileManager, "_persist_active_profile")
|
||||
def test_activate_profile_adds_filters_for_new_tracked_labels(self, mock_persist):
|
||||
"""Labels a profile adds to objects.track get default filters."""
|
||||
err = self.manager.activate_profile("armed")
|
||||
assert err is None
|
||||
|
||||
filters = self.config.cameras["front"].objects.filters
|
||||
for label in ["person", "car", "package"]:
|
||||
assert isinstance(filters[label], RuntimeFilterConfig)
|
||||
|
||||
@patch.object(ProfileManager, "_persist_active_profile")
|
||||
def test_deactivate_profile(self, mock_persist):
|
||||
"""Deactivating a profile restores base config."""
|
||||
|
||||
@@ -1191,7 +1191,11 @@ def apply_section_update(camera_config, section: str, update: dict) -> str | Non
|
||||
Returns:
|
||||
None on success, or an error message string on failure.
|
||||
"""
|
||||
from frigate.config.config import RuntimeFilterConfig, RuntimeMotionConfig
|
||||
from frigate.config.config import (
|
||||
FilterConfig,
|
||||
RuntimeFilterConfig,
|
||||
RuntimeMotionConfig,
|
||||
)
|
||||
|
||||
current = getattr(camera_config, section, None)
|
||||
if current is None:
|
||||
@@ -1224,6 +1228,9 @@ def apply_section_update(camera_config, section: str, update: dict) -> str | Non
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
for label in new_objects.track:
|
||||
new_objects.filters.setdefault(label, FilterConfig())
|
||||
|
||||
# Rebuild RuntimeFilterConfig with merged global + per-object masks
|
||||
for obj_name, filt in new_objects.filters.items():
|
||||
merged_mask = dict(filt.mask)
|
||||
|
||||
@@ -184,8 +184,8 @@ export default function ObjectSettingsView({
|
||||
{config?.cameras[cameraConfig.name]?.webui_url && (
|
||||
<div className="mb-5 text-sm text-muted-foreground">
|
||||
<div className="mt-2 flex flex-row items-center text-primary">
|
||||
<Link
|
||||
to={config?.cameras[cameraConfig.name]?.webui_url ?? ""}
|
||||
<a
|
||||
href={config?.cameras[cameraConfig.name]?.webui_url ?? ""}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline"
|
||||
@@ -194,7 +194,7 @@ export default function ObjectSettingsView({
|
||||
camera: cameraName,
|
||||
})}
|
||||
<LuExternalLink className="ml-2 inline-flex size-3" />
|
||||
</Link>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user