mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-12-03 18:57:08 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0143b2d831 | ||
|
|
a74b1e9f55 |
@@ -1667,6 +1667,18 @@ async def chat_completion(
|
||||
yield _emit_chain()
|
||||
|
||||
yield _emit_chain()
|
||||
if stream_iterations >= max_iterations:
|
||||
# Without this the turn ends on tool results with no answer,
|
||||
# and the client has nothing to tell the user.
|
||||
logger.warning(
|
||||
"Max tool iterations (%d) reached in chat stream", max_iterations
|
||||
)
|
||||
yield _emit(
|
||||
{
|
||||
"type": "error",
|
||||
"error": "I reached the maximum number of tool call iterations. Please try rephrasing your question.",
|
||||
}
|
||||
)
|
||||
yield _emit({"type": "done"})
|
||||
|
||||
return StreamingResponse(
|
||||
|
||||
@@ -219,6 +219,110 @@ test.describe("Chat — streaming @medium", () => {
|
||||
).toBeVisible({ timeout: 5_000 });
|
||||
});
|
||||
|
||||
test("each model call's reasoning renders with its own message", async ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
const toolTurn = [
|
||||
{ role: "system", content: "sys" },
|
||||
{ role: "user", content: "find people" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search_objects",
|
||||
arguments: '{"label":"person"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ role: "tool", tool_call_id: "call_1", content: "[]" },
|
||||
];
|
||||
await installChatStreamOverride(frigateApp, [
|
||||
{ type: "reasoning", delta: "first thought" },
|
||||
{ type: "messages", messages: toolTurn },
|
||||
{ type: "reasoning", delta: "second thought" },
|
||||
{ type: "content", delta: "No people found." },
|
||||
{
|
||||
type: "messages",
|
||||
messages: [
|
||||
...toolTurn,
|
||||
{ role: "assistant", content: "No people found." },
|
||||
],
|
||||
},
|
||||
{ type: "done" },
|
||||
]);
|
||||
await frigateApp.goto("/chat");
|
||||
const input = frigateApp.page.getByPlaceholder(/ask/i);
|
||||
await expect(input).toBeVisible({ timeout: 10_000 });
|
||||
await input.fill("find people");
|
||||
await input.press("Enter");
|
||||
|
||||
await expect(frigateApp.page.getByText("No people found.")).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
// Two separate, collapsed reasoning bubbles; expanding both shows each
|
||||
// trace on its own rather than one concatenated block.
|
||||
const toggles = frigateApp.page.getByRole("button", {
|
||||
name: /show reasoning/i,
|
||||
});
|
||||
await expect(toggles).toHaveCount(2);
|
||||
// Expanding one relabels it to "Hide reasoning", so click the first
|
||||
// remaining "Show" toggle twice.
|
||||
await toggles.first().click();
|
||||
await expect(toggles).toHaveCount(1);
|
||||
await toggles.first().click();
|
||||
await expect(
|
||||
frigateApp.page.locator("pre", { hasText: /^first thought$/ }),
|
||||
).toHaveCount(1);
|
||||
await expect(
|
||||
frigateApp.page.locator("pre", { hasText: /^second thought$/ }),
|
||||
).toHaveCount(1);
|
||||
});
|
||||
|
||||
test("a turn that ends without a final answer keeps its tool calls", async ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
const toolTurn = [
|
||||
{ role: "system", content: "sys" },
|
||||
{ role: "user", content: "find people" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search_objects",
|
||||
arguments: '{"label":"person"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ role: "tool", tool_call_id: "call_1", content: "[]" },
|
||||
];
|
||||
await installChatStreamOverride(frigateApp, [
|
||||
{ type: "messages", messages: toolTurn },
|
||||
{ type: "messages", messages: toolTurn },
|
||||
{ type: "error", error: "iteration limit" },
|
||||
{ type: "done" },
|
||||
]);
|
||||
await frigateApp.goto("/chat");
|
||||
const input = frigateApp.page.getByPlaceholder(/ask/i);
|
||||
await expect(input).toBeVisible({ timeout: 10_000 });
|
||||
await input.fill("find people");
|
||||
await input.press("Enter");
|
||||
|
||||
await expect(
|
||||
frigateApp.page.getByRole("alert").filter({ hasText: /iteration limit/ }),
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
await expect(frigateApp.page.getByText(/search objects/i)).toBeVisible();
|
||||
});
|
||||
|
||||
test("assistant markdown renders only same-origin images", async ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
@@ -307,6 +411,69 @@ test.describe("Chat — stop @medium", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Chat — new chat @medium", () => {
|
||||
test("New chat during a tool-call turn stays cleared", async ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
const toolTurn = [
|
||||
{ role: "system", content: "sys" },
|
||||
{ role: "user", content: "find people" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search_objects",
|
||||
arguments: '{"label":"person"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ role: "tool", tool_call_id: "call_1", content: "[]" },
|
||||
];
|
||||
// The mocked stream ignores the abort signal, so its remaining chunks
|
||||
// and onDone still arrive after New chat: the stale request must not
|
||||
// write them into the cleared chat.
|
||||
await installChatStreamOverride(
|
||||
frigateApp,
|
||||
[
|
||||
{ type: "messages", messages: toolTurn },
|
||||
{ type: "content", delta: "Still answering" },
|
||||
{
|
||||
type: "messages",
|
||||
messages: [
|
||||
...toolTurn,
|
||||
{ role: "assistant", content: "Still answering" },
|
||||
],
|
||||
},
|
||||
{ type: "done" },
|
||||
],
|
||||
{ chunkDelayMs: 400 },
|
||||
);
|
||||
await frigateApp.goto("/chat");
|
||||
const input = frigateApp.page.getByPlaceholder(/ask/i);
|
||||
await expect(input).toBeVisible({ timeout: 10_000 });
|
||||
await input.fill("find people");
|
||||
await input.press("Enter");
|
||||
|
||||
await expect(frigateApp.page.getByText(/search objects/i)).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await frigateApp.page.getByRole("button", { name: "New chat" }).click();
|
||||
|
||||
// Outlast the remaining chunks, then confirm nothing came back.
|
||||
await frigateApp.page.waitForTimeout(1_500);
|
||||
await expect(
|
||||
frigateApp.page.getByRole("heading", { level: 1 }),
|
||||
).toBeVisible();
|
||||
await expect(frigateApp.page.getByText(/search objects/i)).toHaveCount(0);
|
||||
await expect(frigateApp.page.getByText("find people")).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Chat — error @medium", () => {
|
||||
test("non-OK response renders an error banner", async ({ frigateApp }) => {
|
||||
await installChatStreamOverride(frigateApp, [], { status: 500 });
|
||||
|
||||
@@ -34,9 +34,10 @@ export function ReasoningBubble({
|
||||
const { t } = useTranslation(["views/chat"]);
|
||||
// Open while the model is still mid-thought (no answer tokens yet);
|
||||
// once the answer begins, collapse on its own but let the user reopen.
|
||||
const [open, setOpen] = useState(true);
|
||||
// Reasoning that is already finished on mount starts collapsed.
|
||||
const [open, setOpen] = useState(!answerStarted);
|
||||
const userInteractedRef = useRef(false);
|
||||
const lastAutoState = useRef(true);
|
||||
const lastAutoState = useRef(!answerStarted);
|
||||
|
||||
useEffect(() => {
|
||||
if (userInteractedRef.current) return;
|
||||
@@ -66,6 +67,7 @@ export function ReasoningBubble({
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={label}
|
||||
className="h-auto w-full min-w-0 justify-start gap-2 whitespace-normal p-0 text-left text-xs hover:bg-transparent"
|
||||
>
|
||||
<Tooltip>
|
||||
|
||||
+94
-22
@@ -30,6 +30,12 @@ import {
|
||||
toolResponsesById,
|
||||
} from "@/utils/chatUtil";
|
||||
|
||||
/**
|
||||
* The in-flight turn. `content`, `reasoning`, and `stats` cover only the
|
||||
* current model call; each time the backend emits the chain they are attached
|
||||
* to the assistant message that call produced and reset, so every round of
|
||||
* reasoning stays with its own tool calls.
|
||||
*/
|
||||
type StreamingTurn = {
|
||||
content: string;
|
||||
reasoning: string;
|
||||
@@ -152,52 +158,114 @@ export default function ChatPage() {
|
||||
abortRef.current = controller;
|
||||
|
||||
let chain: ChatMessage[] = [];
|
||||
let stats: ChatStats | undefined;
|
||||
let reasoning = "";
|
||||
let hadError = false;
|
||||
let approvals: PendingToolCall[] | null = null;
|
||||
// Reasoning and stats for the current model call, attached to the
|
||||
// assistant message it produces once that message shows up in the chain.
|
||||
let segmentReasoning = "";
|
||||
let segmentStats: ChatStats | undefined;
|
||||
let seenChainLength = 0;
|
||||
const extrasByIndex = new Map<
|
||||
number,
|
||||
Pick<ChatMessage, "reasoning" | "stats">
|
||||
>();
|
||||
|
||||
// The backend never sees reasoning or stats, so the chain it returns
|
||||
// lacks them. Restore them from earlier turns and from this turn's
|
||||
// model calls. The backend prepends a system message on the first turn.
|
||||
const decorate = (raw: ChatMessage[]): ChatMessage[] => {
|
||||
const offset =
|
||||
raw[0]?.role === "system" && messagesToSend[0]?.role !== "system"
|
||||
? 1
|
||||
: 0;
|
||||
return raw.map((m, i) => {
|
||||
const prior = i >= offset ? messagesToSend[i - offset] : undefined;
|
||||
const extras = extrasByIndex.get(i);
|
||||
const reasoning = extras?.reasoning ?? prior?.reasoning;
|
||||
const stats = extras?.stats ?? prior?.stats;
|
||||
return reasoning || stats ? { ...m, reasoning, stats } : m;
|
||||
});
|
||||
};
|
||||
|
||||
// This request owns the chat until New chat or a newer request replaces
|
||||
// abortRef. Callbacks from a request that lost ownership (including the
|
||||
// onDone that follows an abort) must not touch the current chat.
|
||||
const owns = () => abortRef.current === controller;
|
||||
|
||||
await streamChatCompletion(
|
||||
url,
|
||||
headers,
|
||||
toWire(messagesToSend),
|
||||
{
|
||||
onContentDelta: (delta) =>
|
||||
setStreaming((s) => (s ? { ...s, content: s.content + delta } : s)),
|
||||
onContentDelta: (delta) => {
|
||||
if (!owns()) return;
|
||||
setStreaming((s) => (s ? { ...s, content: s.content + delta } : s));
|
||||
},
|
||||
onReasoningDelta: (delta) => {
|
||||
reasoning += delta;
|
||||
if (!owns()) return;
|
||||
segmentReasoning += delta;
|
||||
setStreaming((s) =>
|
||||
s ? { ...s, reasoning: s.reasoning + delta } : s,
|
||||
);
|
||||
},
|
||||
onChain: (fullChain) => {
|
||||
chain = fullChain;
|
||||
setStreaming((s) => (s ? { ...s, chain: fullChain } : s));
|
||||
if (!owns()) return;
|
||||
// Credit the current call's reasoning to the newest assistant
|
||||
// message added since the last chain, then start a new segment.
|
||||
for (let i = fullChain.length - 1; i >= seenChainLength; i--) {
|
||||
if (fullChain[i].role !== "assistant") continue;
|
||||
if (segmentReasoning || segmentStats) {
|
||||
extrasByIndex.set(i, {
|
||||
reasoning: segmentReasoning || undefined,
|
||||
stats: segmentStats,
|
||||
});
|
||||
}
|
||||
segmentReasoning = "";
|
||||
segmentStats = undefined;
|
||||
break;
|
||||
}
|
||||
seenChainLength = fullChain.length;
|
||||
chain = decorate(fullChain);
|
||||
const decorated = chain;
|
||||
setStreaming((s) =>
|
||||
s
|
||||
? {
|
||||
...s,
|
||||
chain: decorated,
|
||||
content: "",
|
||||
reasoning: segmentReasoning,
|
||||
stats: segmentStats,
|
||||
}
|
||||
: s,
|
||||
);
|
||||
},
|
||||
onStats: (s) => {
|
||||
stats = s;
|
||||
if (!owns()) return;
|
||||
segmentStats = s;
|
||||
setStreaming((cur) => (cur ? { ...cur, stats: s } : cur));
|
||||
},
|
||||
onApprovalRequired: (toolCalls) => {
|
||||
approvals = toolCalls;
|
||||
},
|
||||
onError: (message) => {
|
||||
if (!owns()) return;
|
||||
hadError = true;
|
||||
setError(message);
|
||||
},
|
||||
onDone: () => {
|
||||
if (!owns()) return;
|
||||
abortRef.current = null;
|
||||
loadingRef.current = false;
|
||||
setIsLoading(false);
|
||||
setStreaming(null);
|
||||
const lastMsg = chain[chain.length - 1];
|
||||
// Keep whatever the backend got through, even when the turn ends
|
||||
// without a final answer (error, stop, or tool iteration limit).
|
||||
// Dropping it would make the tool calls and reasoning vanish.
|
||||
if (chain.length === 0) return;
|
||||
const committed = chain;
|
||||
setMessages(committed);
|
||||
const lastMsg = committed[committed.length - 1];
|
||||
if (!hadError && lastMsg?.role === "assistant") {
|
||||
const committed = chain.map((m, i) =>
|
||||
i === chain.length - 1
|
||||
? { ...m, reasoning: reasoning || undefined, stats }
|
||||
: m,
|
||||
);
|
||||
setMessages(committed);
|
||||
if (approvals?.length) {
|
||||
// Calls to always-allowed tools are answered here without
|
||||
// prompting; anything else waits for the user.
|
||||
@@ -302,8 +370,10 @@ export default function ChatPage() {
|
||||
);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
// Keep abortRef pointing at the stopped request so its onDone can still
|
||||
// commit the partial chain. A message sent before that onDone fires
|
||||
// replaces abortRef, and the stale onDone then does nothing.
|
||||
abortRef.current?.abort();
|
||||
abortRef.current = null;
|
||||
loadingRef.current = false;
|
||||
setIsLoading(false);
|
||||
setStreaming(null);
|
||||
@@ -312,8 +382,11 @@ export default function ChatPage() {
|
||||
}, []);
|
||||
|
||||
const startNewChat = useCallback(() => {
|
||||
abortRef.current?.abort();
|
||||
// Give up ownership before aborting so the aborted request's onDone
|
||||
// cannot restore the conversation being cleared.
|
||||
const controller = abortRef.current;
|
||||
abortRef.current = null;
|
||||
controller?.abort();
|
||||
loadingRef.current = false;
|
||||
setIsLoading(false);
|
||||
setStreaming(null);
|
||||
@@ -377,13 +450,12 @@ export default function ChatPage() {
|
||||
|
||||
return (
|
||||
<div key={i} className="flex flex-col gap-2">
|
||||
{calls.length > 0 && <ToolCallsGroup toolCalls={calls} />}
|
||||
{/* Messages in the chain are finished model calls, so their
|
||||
reasoning is complete even when they ended in tool calls. */}
|
||||
{hasText(msg.reasoning) && (
|
||||
<ReasoningBubble
|
||||
reasoning={msg.reasoning}
|
||||
answerStarted={!!contentText}
|
||||
/>
|
||||
<ReasoningBubble reasoning={msg.reasoning} answerStarted />
|
||||
)}
|
||||
{calls.length > 0 && <ToolCallsGroup toolCalls={calls} />}
|
||||
{contentText && (
|
||||
<MessageBubble
|
||||
role="assistant"
|
||||
|
||||
Reference in New Issue
Block a user