Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(transport): keep prompt prefix stable across tool-call turns
Akarshan Biswas449b2413af55
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 55710bb76..cadc3e082 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -44,7 +44,7 @@ import { mcpOrchestrator } from '@/lib/mcp-orchestrator'import { isRouterModelSelectable } from '@/lib/mcp-router-model-filter'import { encodeAudioSentinel, parseAudioDataUrl } from '@/lib/audio-sentinel'import { encodeVideoSentinel, parseVideoDataUrl } from '@/lib/video-sentinel'-import { isPredefinedRemoteProvider, getProviderApiType } from '@/lib/providerCaps'+import { isPredefinedRemoteProvider } from '@/lib/providerCaps'import { paramsSettings } from '@/lib/predefinedParams'export type TokenUsageCallback = (@@ -497,6 +497,63 @@ export function resolveOrphanToolCalls(messages: UIMessage[]): UIMessage[] {})}+/**+ * Split any assistant message whose parts place non-tool content (text,+ * reasoning, file) AFTER tool-call parts into consecutive assistant messages,+ * one per "wave". This is required for two reasons:+ *+ * 1. Correctness: the Claude API rejects an assistant turn that interleaves+ * tool_use with text (error 400); it needs tool_use / tool_result pairing.+ * 2. Prompt-cache stability: when a tool-call turn completes, the AI SDK stores+ * the follow-up text in the SAME assistant UIMessage as the tool call, so+ * `convertToModelMessages` renders `assistant(tool-call, text)` then+ * `tool(result)`. But that turn was generated in two requests — the cache+ * was seeded with `assistant(tool-call)` then `tool(result)`, with no text+ * yet. Splitting restores the generated order `assistant(tool-call)` ->+ * `tool(result)` -> `assistant(text)`, so the prefix stays byte-identical+ * across turns and llama.cpp reuses the KV cache.+ *+ * A message with no tool parts, or with all non-tool parts before the tool+ * parts, is returned unchanged.+ */+export function splitAssistantToolWaves(messages: UIMessage[]): UIMessage[] {+ return messages.flatMap((message) => {+ if (message.role !== 'assistant') return [message]++ const parts = Array.isArray(message.parts) ? message.parts : []+ if (parts.length === 0) return [message]++ const isToolPart = (p: (typeof parts)[number]) =>+ typeof p.type === 'string' && p.type.startsWith('tool-')++ const waves: (typeof parts)[] = []+ let currentWave: typeof parts = []+ let seenToolParts = false++ for (const part of parts) {+ if (isToolPart(part)) {+ seenToolParts = true+ currentWave.push(part)+ } else if (seenToolParts) {+ waves.push(currentWave)+ currentWave = [part]+ seenToolParts = false+ } else {+ currentWave.push(part)+ }+ }+ if (currentWave.length > 0) waves.push(currentWave)++ if (waves.length <= 1) return [message]++ return waves.map((waveParts, i) => ({+ ...message,+ id: `${message.id}_w${i}`,+ parts: waveParts,+ }))+ })+}+export function coalesceMessagesForAlternation(messages: UIMessage[]): UIMessage[] {@@ -1054,55 +1111,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {await this.refreshTools(options.abortSignal)- // Fix for Anthropic serial tool-use (error 400): when an assistant message- // contains tool parts interleaved with text parts (serial tool calls),- // split it into separate messages so convertToModelMessages produces the- // tool_use / tool_result pairing that the Claude API requires.- // See: https://platform.claude.com/docs/en/agents-and-tools/tool-use/implement-tool-use#parallel-tool-use- const effectiveApiType = getProviderApiType(provider)- const messagesToConvert = (() => {- if (effectiveApiType !== 'anthropic') {- return options.messages- }- return options.messages.flatMap((message) => {- if (message.role !== 'assistant') return [message]-- const parts = Array.isArray(message.parts) ? message.parts : []- if (parts.length === 0) return [message]-- const isToolPart = (p: (typeof parts)[number]) =>- p.type.startsWith('tool-')-- const waves: (typeof parts)[] = []- let currentWave: typeof parts = []- let seenToolParts = false-- for (const part of parts) {- if (isToolPart(part)) {- seenToolParts = true- currentWave.push(part)- } else if (!isToolPart(part) && seenToolParts) {- // Any non-tool part (text, reasoning, file, etc.) after tool parts- // marks the start of a new wave- waves.push(currentWave)- currentWave = [part]- seenToolParts = false- } else {- currentWave.push(part)- }- }- if (currentWave.length > 0) waves.push(currentWave)-- // No serial tool calls detected — return original message unchanged- if (waves.length <= 1) return [message]-- return waves.map((waveParts, i) => ({- ...message,- id: `${message.id}_w${i}`,- parts: waveParts,- }))- })- })()+ // Split assistant turns that place text after tool calls into separate+ // messages. Required by the Claude API (tool_use / tool_result pairing) and+ // it keeps the prompt prefix byte-identical across turns so llama.cpp reuses+ // the KV cache. See `splitAssistantToolWaves`.+ const messagesToConvert = splitAssistantToolWaves(options.messages)const inferenceParams = this.getActiveInferenceParams()diff --git a/web-app/src/lib/prompt-cache-toolcall.test.ts b/web-app/src/lib/prompt-cache-toolcall.test.tsnew file mode 100644index 000000000..0860cfbc1--- /dev/null+++ b/web-app/src/lib/prompt-cache-toolcall.test.ts@@ -0,0 +1,123 @@+import { describe, it, expect } from 'vitest'+import { convertToModelMessages, type UIMessage } from 'ai'+import {+ coalesceMessagesForAlternation,+ resolveOrphanToolCalls,+ splitAssistantToolWaves,+} from './custom-chat-transport'++/**+ * Cache validation: llama.cpp reuses the KV cache only when the new prompt's+ * prefix is byte-identical to the previous one. When a turn involves a+ * (MCP) tool call, the assistant tool-call turn and its tool result must+ * survive into the NEXT turn's prompt unchanged, so the prefix up to that+ * point stays stable and the cache is reused.+ */++const pipeline = async (messages: UIMessage[]) =>+ convertToModelMessages(+ coalesceMessagesForAlternation(+ resolveOrphanToolCalls(splitAssistantToolWaves(messages))+ )+ )++describe('prompt cache stability across a tool-call turn', () => {+ const toolTurn: UIMessage = {+ id: 'a1',+ role: 'assistant',+ parts: [+ {+ type: 'tool-mcp__fs__list',+ toolCallId: 'call_1',+ input: { path: '/tmp' },+ state: 'output-available',+ output: { files: ['a', 'b'] },+ },+ { type: 'text', text: 'There are two files.' },+ ],+ } as unknown as UIMessage++ const user1: UIMessage = {+ id: 'u1',+ role: 'user',+ parts: [{ type: 'text', text: 'What files are in /tmp?' }],+ } as UIMessage++ const user2: UIMessage = {+ id: 'u2',+ role: 'user',+ parts: [{ type: 'text', text: 'thanks' }],+ } as UIMessage++ it('keeps the cached tool-call prefix identical on the next turn', async () => {+ // A tool-call turn is two requests. The FIRST follow-up request (which+ // seeds the KV cache after the tool ran) carries the assistant tool-call+ // with no assistant text yet, followed by the tool result:+ const toolCallOnly: UIMessage = {+ id: 'a1',+ role: 'assistant',+ parts: [+ {+ type: 'tool-mcp__fs__list',+ toolCallId: 'call_1',+ input: { path: '/tmp' },+ state: 'output-available',+ output: { files: ['a', 'b'] },+ },+ ],+ } as unknown as UIMessage+ const cachedPrompt = await pipeline([user1, toolCallOnly])++ // On the NEXT user turn the final assistant text has been folded into the+ // same message as the tool call.+ const nextPrompt = await pipeline([user1, toolTurn, user2])++ // For the KV cache to be reused, the prefix up to the tool result must be+ // byte-identical to what was cached.+ const prefix = nextPrompt.slice(0, cachedPrompt.length)+ expect(prefix).toEqual(cachedPrompt)+ })++ it('preserves the MCP tool_call and its result in the next prompt', async () => {+ const prompt = await pipeline([user1, toolTurn, user2])+ const serialized = JSON.stringify(prompt)++ expect(serialized).toContain('call_1')+ expect(serialized).toContain('mcp__fs__list')+ // The tool result must still be present (tool_use paired with tool_result).+ const hasToolResult = prompt.some(+ (m) =>+ m.role === 'tool' &&+ Array.isArray(m.content) &&+ m.content.some(+ (c) => (c as { toolCallId?: string }).toolCallId === 'call_1'+ )+ )+ expect(hasToolResult).toBe(true)+ })++ it('renders the tool result before the follow-up assistant text', async () => {+ const prompt = await pipeline([user1, toolTurn, user2])+ const roles = prompt.map((m) => m.role)++ const toolCallIdx = prompt.findIndex(+ (m) =>+ m.role === 'assistant' &&+ Array.isArray(m.content) &&+ m.content.some((c) => (c as { type?: string }).type === 'tool-call')+ )+ const toolResultIdx = roles.indexOf('tool')+ const textIdx = prompt.findIndex(+ (m) =>+ m.role === 'assistant' &&+ Array.isArray(m.content) &&+ m.content.some(+ (c) => (c as { type?: string; text?: string }).text === 'There are two files.'+ )+ )++ expect(toolCallIdx).toBeGreaterThanOrEqual(0)+ expect(toolResultIdx).toBeGreaterThan(toolCallIdx)+ expect(textIdx).toBeGreaterThan(toolResultIdx)+ })+})