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,
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user