mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-12-03 10:47:06 +03:00
Compare commits
1
Commits
dev
...
chat-reasoning
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a74b1e9f55 |
@@ -1667,6 +1667,18 @@ async def chat_completion(
|
|||||||
yield _emit_chain()
|
yield _emit_chain()
|
||||||
|
|
||||||
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"})
|
yield _emit({"type": "done"})
|
||||||
|
|
||||||
return StreamingResponse(
|
return StreamingResponse(
|
||||||
|
|||||||
@@ -219,6 +219,110 @@ test.describe("Chat — streaming @medium", () => {
|
|||||||
).toBeVisible({ timeout: 5_000 });
|
).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 ({
|
test("assistant markdown renders only same-origin images", async ({
|
||||||
frigateApp,
|
frigateApp,
|
||||||
}) => {
|
}) => {
|
||||||
|
|||||||
@@ -34,9 +34,10 @@ export function ReasoningBubble({
|
|||||||
const { t } = useTranslation(["views/chat"]);
|
const { t } = useTranslation(["views/chat"]);
|
||||||
// Open while the model is still mid-thought (no answer tokens yet);
|
// 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.
|
// 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 userInteractedRef = useRef(false);
|
||||||
const lastAutoState = useRef(true);
|
const lastAutoState = useRef(!answerStarted);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (userInteractedRef.current) return;
|
if (userInteractedRef.current) return;
|
||||||
@@ -66,6 +67,7 @@ export function ReasoningBubble({
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
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"
|
className="h-auto w-full min-w-0 justify-start gap-2 whitespace-normal p-0 text-left text-xs hover:bg-transparent"
|
||||||
>
|
>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
|
|||||||
+73
-18
@@ -30,6 +30,12 @@ import {
|
|||||||
toolResponsesById,
|
toolResponsesById,
|
||||||
} from "@/utils/chatUtil";
|
} 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 = {
|
type StreamingTurn = {
|
||||||
content: string;
|
content: string;
|
||||||
reasoning: string;
|
reasoning: string;
|
||||||
@@ -152,10 +158,34 @@ export default function ChatPage() {
|
|||||||
abortRef.current = controller;
|
abortRef.current = controller;
|
||||||
|
|
||||||
let chain: ChatMessage[] = [];
|
let chain: ChatMessage[] = [];
|
||||||
let stats: ChatStats | undefined;
|
|
||||||
let reasoning = "";
|
|
||||||
let hadError = false;
|
let hadError = false;
|
||||||
let approvals: PendingToolCall[] | null = null;
|
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;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
await streamChatCompletion(
|
await streamChatCompletion(
|
||||||
url,
|
url,
|
||||||
@@ -165,17 +195,43 @@ export default function ChatPage() {
|
|||||||
onContentDelta: (delta) =>
|
onContentDelta: (delta) =>
|
||||||
setStreaming((s) => (s ? { ...s, content: s.content + delta } : s)),
|
setStreaming((s) => (s ? { ...s, content: s.content + delta } : s)),
|
||||||
onReasoningDelta: (delta) => {
|
onReasoningDelta: (delta) => {
|
||||||
reasoning += delta;
|
segmentReasoning += delta;
|
||||||
setStreaming((s) =>
|
setStreaming((s) =>
|
||||||
s ? { ...s, reasoning: s.reasoning + delta } : s,
|
s ? { ...s, reasoning: s.reasoning + delta } : s,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
onChain: (fullChain) => {
|
onChain: (fullChain) => {
|
||||||
chain = fullChain;
|
// Credit the current call's reasoning to the newest assistant
|
||||||
setStreaming((s) => (s ? { ...s, chain: fullChain } : s));
|
// 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) => {
|
onStats: (s) => {
|
||||||
stats = s;
|
segmentStats = s;
|
||||||
setStreaming((cur) => (cur ? { ...cur, stats: s } : cur));
|
setStreaming((cur) => (cur ? { ...cur, stats: s } : cur));
|
||||||
},
|
},
|
||||||
onApprovalRequired: (toolCalls) => {
|
onApprovalRequired: (toolCalls) => {
|
||||||
@@ -190,14 +246,14 @@ export default function ChatPage() {
|
|||||||
loadingRef.current = false;
|
loadingRef.current = false;
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
setStreaming(null);
|
setStreaming(null);
|
||||||
const lastMsg = chain[chain.length - 1];
|
// Keep whatever the backend got through, even when the turn ends
|
||||||
if (!hadError && lastMsg?.role === "assistant") {
|
// without a final answer (error, stop, or tool iteration limit).
|
||||||
const committed = chain.map((m, i) =>
|
// Dropping it would make the tool calls and reasoning vanish.
|
||||||
i === chain.length - 1
|
if (chain.length === 0) return;
|
||||||
? { ...m, reasoning: reasoning || undefined, stats }
|
const committed = chain;
|
||||||
: m,
|
|
||||||
);
|
|
||||||
setMessages(committed);
|
setMessages(committed);
|
||||||
|
const lastMsg = committed[committed.length - 1];
|
||||||
|
if (!hadError && lastMsg?.role === "assistant") {
|
||||||
if (approvals?.length) {
|
if (approvals?.length) {
|
||||||
// Calls to always-allowed tools are answered here without
|
// Calls to always-allowed tools are answered here without
|
||||||
// prompting; anything else waits for the user.
|
// prompting; anything else waits for the user.
|
||||||
@@ -377,13 +433,12 @@ export default function ChatPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={i} className="flex flex-col gap-2">
|
<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) && (
|
{hasText(msg.reasoning) && (
|
||||||
<ReasoningBubble
|
<ReasoningBubble reasoning={msg.reasoning} answerStarted />
|
||||||
reasoning={msg.reasoning}
|
|
||||||
answerStarted={!!contentText}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
|
{calls.length > 0 && <ToolCallsGroup toolCalls={calls} />}
|
||||||
{contentText && (
|
{contentText && (
|
||||||
<MessageBubble
|
<MessageBubble
|
||||||
role="assistant"
|
role="assistant"
|
||||||
|
|||||||
Reference in New Issue
Block a user