Harden chat tool approvals (#25062)

* use server-generated tool call ids and drop remote images from chat messages

Chat write-tool approvals were keyed by the provider's tool call id, but Gemini uses the function name as the id and Ollama falls back to call_0, call_1, so a later or repeated write call in the same request reused an earlier approval and ran without a prompt. Each tool call the model returns now gets a unique server-generated id, and the Gemini plugin resolves a tool result's function name from the assistant's tool calls instead of from the id. Client message content now keeps only text parts and data:image/ image parts, so OpenAI-compatible servers and llama-server are never handed a remote URL to fetch.

* remove client image filter from chat messages
This commit is contained in:
Josh Hawkins
2026-11-24 06:35:19 -07:00
committed by GitHub
parent 212ebca746
commit 50b976889b
4 changed files with 82 additions and 2 deletions
+14 -2
View File
@@ -6,6 +6,7 @@ import json
import logging import logging
import operator import operator
import time import time
import uuid
from datetime import datetime from datetime import datetime
from functools import reduce from functools import reduce
from typing import Any, Literal from typing import Any, Literal
@@ -1280,6 +1281,14 @@ def _pending_tool_calls_from_tail(
return parse_tool_calls_from_message(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( def _tool_calls_awaiting_approval(
pending_tool_calls: list[dict[str, Any]], pending_tool_calls: list[dict[str, Any]],
body: ChatCompletionRequest, body: ChatCompletionRequest,
@@ -1605,6 +1614,7 @@ async def chat_completion(
return return
requested = msg.get("tool_calls") requested = msg.get("tool_calls")
if requested: if requested:
requested = _with_server_ids(requested)
stream_iterations += 1 stream_iterations += 1
conversation.append( conversation.append(
build_assistant_message_for_conversation( build_assistant_message_for_conversation(
@@ -1690,13 +1700,15 @@ async def chat_completion(
status_code=500, 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( conversation.append(
build_assistant_message_for_conversation( 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: if not pending_tool_calls:
logger.debug( logger.debug(
f"Chat completion finished with final answer (iterations: {tool_iterations})" f"Chat completion finished with final answer (iterations: {tool_iterations})"
+15
View File
@@ -67,6 +67,17 @@ def _decode_data_uri(url: str) -> tuple[str, bytes] | None:
return 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]: def _parts_from_content(content: Any) -> list[types.Part]:
"""Convert OpenAI-style message content (str or multimodal list) to Gemini parts.""" """Convert OpenAI-style message content (str or multimodal list) to Gemini parts."""
if isinstance(content, list): if isinstance(content, list):
@@ -458,6 +469,7 @@ class GeminiClient(GenAIClient):
try: try:
# Convert messages to Gemini format # Convert messages to Gemini format
gemini_messages: list[types.Content] = [] gemini_messages: list[types.Content] = []
tool_names = _tool_names_by_id(messages)
for msg in messages: for msg in messages:
role = msg.get("role", "user") role = msg.get("role", "user")
content = msg.get("content", "") content = msg.get("content", "")
@@ -520,6 +532,7 @@ class GeminiClient(GenAIClient):
parts=[ parts=[
types.Part.from_function_response( types.Part.from_function_response(
name=msg.get("name") name=msg.get("name")
or tool_names.get(msg.get("tool_call_id") or "")
or msg.get("tool_call_id") or msg.get("tool_call_id")
or "", or "",
response=response_payload, response=response_payload,
@@ -714,6 +727,7 @@ class GeminiClient(GenAIClient):
try: try:
# Convert messages to Gemini format # Convert messages to Gemini format
gemini_messages: list[types.Content] = [] gemini_messages: list[types.Content] = []
tool_names = _tool_names_by_id(messages)
for msg in messages: for msg in messages:
role = msg.get("role", "user") role = msg.get("role", "user")
content = msg.get("content", "") content = msg.get("content", "")
@@ -776,6 +790,7 @@ class GeminiClient(GenAIClient):
parts=[ parts=[
types.Part.from_function_response( types.Part.from_function_response(
name=msg.get("name") name=msg.get("name")
or tool_names.get(msg.get("tool_call_id") or "")
or msg.get("tool_call_id") or msg.get("tool_call_id")
or "", or "",
response=response_payload, response=response_payload,
+17
View File
@@ -22,6 +22,7 @@ from frigate.api.chat import (
_execute_pending_tools, _execute_pending_tools,
_pending_tool_calls_from_tail, _pending_tool_calls_from_tail,
_tool_calls_awaiting_approval, _tool_calls_awaiting_approval,
_with_server_ids,
) )
from frigate.api.defs.request.chat_body import ChatCompletionRequest from frigate.api.defs.request.chat_body import ChatCompletionRequest
from frigate.genai.prompts import ( from frigate.genai.prompts import (
@@ -152,6 +153,22 @@ class TestApprovalHelpers(unittest.TestCase):
body = _body(tool_decisions={"c2": "approve", "c3": "reject"}) body = _body(tool_decisions={"c2": "approve", "c3": "reject"})
self.assertEqual(_tool_calls_awaiting_approval(pending, body, WRITE_TOOLS), []) 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): class TestExecutePendingTools(unittest.TestCase):
def test_rejected_call_is_not_executed(self): def test_rejected_call_is_not_executed(self):
+36
View File
@@ -501,6 +501,42 @@ class TestGeminiProvider(unittest.TestCase):
final = _final_message(_collect(client, MULTIMODAL_MESSAGES)) final = _final_message(_collect(client, MULTIMODAL_MESSAGES))
self.assertEqual(final["content"], "ok") 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): class TestGeminiImageTokens(unittest.TestCase):
def _client(self, count_tokens): def _client(self, count_tokens):