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.
This commit is contained in:
Josh Hawkins
2026-11-23 08:59:30 -06:00
parent 3bca9b8676
commit 0ff8718057
4 changed files with 127 additions and 3 deletions
+36 -3
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
@@ -1274,6 +1275,35 @@ 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 _client_content(content: Any) -> Any:
"""Keep only text parts and inline images from client message content.
Some model servers fetch remote image URLs themselves.
"""
if not isinstance(content, list):
return content
kept = []
for part in content:
if not isinstance(part, dict):
continue
if part.get("type") == "text":
kept.append(part)
elif part.get("type") == "image_url":
image = part.get("image_url")
url = image.get("url") if isinstance(image, dict) else None
if isinstance(url, str) and url.startswith("data:image/"):
kept.append(part)
return kept
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,
@@ -1519,7 +1549,7 @@ async def chat_completion(
for msg in body.messages: for msg in body.messages:
msg_dict = { msg_dict = {
"role": msg.role, "role": msg.role,
"content": msg.content, "content": _client_content(msg.content),
} }
if msg.tool_call_id: if msg.tool_call_id:
msg_dict["tool_call_id"] = msg.tool_call_id msg_dict["tool_call_id"] = msg.tool_call_id
@@ -1599,6 +1629,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(
@@ -1684,13 +1715,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,
+40
View File
@@ -16,12 +16,14 @@ from peewee import SqliteDatabase
from frigate.api.chat import ( from frigate.api.chat import (
TOOL_REJECTED_RESULT, TOOL_REJECTED_RESULT,
_client_content,
_execute_create_export, _execute_create_export,
_execute_get_event_image, _execute_get_event_image,
_execute_get_export_cases, _execute_get_export_cases,
_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 +154,44 @@ 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 TestClientContent(unittest.TestCase):
def test_string_content_is_unchanged(self):
self.assertEqual(_client_content("hi"), "hi")
self.assertIsNone(_client_content(None))
def test_only_text_and_inline_images_are_kept(self):
text = {"type": "text", "text": "look"}
inline = {
"type": "image_url",
"image_url": {"url": "data:image/jpeg;base64,AAAA"},
}
content = [
text,
inline,
{"type": "image_url", "image_url": {"url": "http://frigate:5000/x.jpg"}},
{"type": "image_url", "image_url": "data:image/jpeg;base64,AAAA"},
{"type": "input_audio", "input_audio": {"data": "AAAA"}},
"stray",
]
self.assertEqual(_client_content(content), [text, inline])
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
@@ -500,6 +500,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):