fix chat reasoning not splitting after tool calls

This commit is contained in:
Nicolas Mowen
2026-12-02 16:58:38 -07:00
parent 9b386acaf1
commit a74b1e9f55
4 changed files with 193 additions and 20 deletions
+12
View File
@@ -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(
+104
View File
@@ -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,
}) => {
+4 -2
View File
@@ -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>
+73 -18
View File
@@ -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,10 +158,34 @@ 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;
});
};
await streamChatCompletion(
url,
@@ -165,17 +195,43 @@ export default function ChatPage() {
onContentDelta: (delta) =>
setStreaming((s) => (s ? { ...s, content: s.content + delta } : s)),
onReasoningDelta: (delta) => {
reasoning += delta;
segmentReasoning += delta;
setStreaming((s) =>
s ? { ...s, reasoning: s.reasoning + delta } : s,
);
},
onChain: (fullChain) => {
chain = fullChain;
setStreaming((s) => (s ? { ...s, chain: fullChain } : s));
// 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;
segmentStats = s;
setStreaming((cur) => (cur ? { ...cur, stats: s } : cur));
},
onApprovalRequired: (toolCalls) => {
@@ -190,14 +246,14 @@ export default function ChatPage() {
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.
@@ -377,13 +433,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"