Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion ui-packages/web/src/core/agent/compaction.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import type { AgentMessage } from '@earendil-works/pi-agent-core'
import type { AssistantMessage, Message, ToolResultMessage } from '@earendil-works/pi-ai'
import { describe, expect, it } from 'vitest'
import { type CompactionMessage, planCompaction, projectContext } from './compaction'
import {
autoCompactionEnabled,
type CompactionMessage,
compactionThreshold,
keepRecentFor,
needsCompaction,
planCompaction,
projectContext,
} from './compaction'

const user = (text: string): Message => ({ role: 'user', content: text, timestamp: 1 })

Expand Down Expand Up @@ -144,3 +152,42 @@ describe('planCompaction', () => {
expect(planCompaction([...messages, compaction('done', 1)], 0)).toBeNull()
})
})

describe('when to compact', () => {
it('scales the threshold and what is kept with the window', () => {
const budget = (window: number) => [compactionThreshold(window), keepRecentFor(window)]

expect(budget(1_000_000)).toEqual([512_000, 40_000])
expect(budget(128_000)).toEqual([111_616, 40_000])
expect(budget(32_000)).toEqual([16_000, 6_400])
expect(budget(8_000)).toEqual([4_000, 1_600])
// A window the catalog does not know.
expect(budget(0)).toEqual([512_000, 40_000])
})

it('compacts once the context passes the threshold, and not again after', () => {
const window = 128_000
const messages: AgentMessage[] = [
user('x'.repeat(400_000)),
assistant('y'.repeat(400_000)),
user('z'.repeat(400)),
]

expect(needsCompaction(messages, window)).toBe(true)
expect(needsCompaction([...messages, compaction('short', 2)], window)).toBe(false)
})

it('automates only known windows of at least 128K', () => {
const messages = [user('x'.repeat(2_000_000))]
const smallWindows = [0, 32_000, 127_999]
smallWindows.forEach(window => {
expect(autoCompactionEnabled(window)).toBe(false)
expect(needsCompaction(messages, window)).toBe(false)
})
const supportedWindows = [128_000, 1_000_000]
supportedWindows.forEach(window => {
expect(autoCompactionEnabled(window)).toBe(true)
expect(needsCompaction(messages, window)).toBe(true)
})
})
})
29 changes: 26 additions & 3 deletions ui-packages/web/src/core/agent/compaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,28 @@ export const isCompactionMessage = (message: AgentMessage): message is Compactio
export const compactionSettings = {
/** Room left for the reply; it also bounds the summary's length. */
reserveTokens: 16_384,
/** Recent context kept as it is. */
keepRecentTokens: 20_000,
/** Every request resends the whole context, mostly from the provider's cache, so compacting
* rarely costs less than it loses; very long contexts still answer worse. */
maximumThreshold: 512_000,
/** Recent context kept as it is, enough to quote the last pages read. */
maximumKeep: 40_000,
}

// A window of 0 is one the catalog does not know. Half the window keeps a tiny one usable.
export const compactionThreshold = (contextWindow: number) =>
contextWindow > 0
? Math.min(
compactionSettings.maximumThreshold,
Math.max(contextWindow - compactionSettings.reserveTokens, Math.floor(contextWindow / 2)),
)
: compactionSettings.maximumThreshold

export const autoCompactionEnabled = (contextWindow: number): boolean => contextWindow >= 128_000

// A retention budget, not a bound on the summary or an indivisible message kept with it.
export const keepRecentFor = (contextWindow: number) =>
Math.min(compactionSettings.maximumKeep, Math.floor(0.4 * compactionThreshold(contextWindow)))

const summaryPrefix =
'The conversation history before this point was compacted into the following summary:\n\n<summary>\n'
const summarySuffix = '\n</summary>'
Expand Down Expand Up @@ -100,7 +118,7 @@ const isCutPoint = (message: AgentMessage) =>
// valid point at or after it. Returns null when there is nothing to fold away.
export const planCompaction = (
conversation: readonly AgentMessage[],
keepRecentTokens = compactionSettings.keepRecentTokens,
keepRecentTokens: number,
): CompactionPlan | null => {
const last = conversation.at(-1)
if (!last || isCompactionMessage(last)) return null
Expand Down Expand Up @@ -139,6 +157,11 @@ export const planCompaction = (
}
}

// Whether the context the provider would be sent has passed the threshold.
export const needsCompaction = (messages: readonly AgentMessage[], contextWindow: number) =>
autoCompactionEnabled(contextWindow) &&
estimateContextTokens(projectContext(messages)).tokens > compactionThreshold(contextWindow)

const toolResultLimit = 2_000

const truncate = (text: string) =>
Expand Down
3 changes: 2 additions & 1 deletion ui-packages/web/src/features/assistant/compaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import {
type CompactionMessage,
compactionSettings,
keepRecentFor,
planCompaction,
serializeConversation,
} from '../../core/agent/compaction'
Expand Down Expand Up @@ -145,7 +146,7 @@ export const compactConversation = async (
conversation: readonly AgentMessage[],
signal?: AbortSignal,
): Promise<CompactionMessage | null> => {
const plan = planCompaction(conversation)
const plan = planCompaction(conversation, keepRecentFor(model.contextWindow))
if (!plan) return null
const { firstKept, history, turnPrefix, previousSummary, tokensBefore } = plan
const [summary, prefix] = await Promise.all([
Expand Down
69 changes: 65 additions & 4 deletions ui-packages/web/src/features/assistant/create-reader-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@ const xlsx = vi.hoisted(() => ({ read: vi.fn() }))
vi.mock('read-excel-file/browser', () => ({ default: xlsx.read }))

const config = await createModelRuntime(modelConfig)
const event = (delta: unknown, finish: string | null = null) =>
`data: ${JSON.stringify({ id: 'reply', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`
const reply = (text: string) =>
new Response(`${event({ content: text }) + event({}, 'stop')}data: [DONE]\n\n`, {
const event = (delta: unknown, finish: string | null = null, tokens = 0) =>
`data: ${JSON.stringify({ id: 'reply', choices: [{ index: 0, delta, finish_reason: finish }], ...(tokens ? { usage: { prompt_tokens: tokens, completion_tokens: 0, total_tokens: tokens } } : {}) })}\n\n`
const reply = (text: string, tokens = 0) =>
new Response(`${event({ content: text }) + event({}, 'stop', tokens)}data: [DONE]\n\n`, {
headers: { 'Content-Type': 'text/event-stream' },
})
const call = (name: string, args: unknown) =>
Expand All @@ -87,6 +87,67 @@ const localTools = () => createLocalTools(emptyState, writeStoredTextFile, moveS
const session = { id: 'test-conversation', messages: [], ...resolveModelSelection(config) }

describe('reader agent', () => {
it.each([0, 32_000, 127_999, 128_000])(
'automates between tool turns only for a supported %i window',
async window => {
const notifications = vi.fn()
const fetchModel = vi
.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(reply('x'.repeat(150_000), 120_000))
const agent = createReaderAgent(config, localTools(), {
...session,
model: { ...session.model, contextWindow: window },
onCompactionChange: notifications,
})
await agent.prompt('Earlier question')
const requests: string[] = []
fetchModel.mockImplementation(async (_url, init) => {
const summary = String(init?.body).includes('context summarization assistant')
requests.push(summary ? 'summary' : 'chat')
if (summary) return reply('Earlier question summarized')
return requests.length === 1 ? call('get_reader_state', {}) : reply('Finished')
})
await agent.prompt('Read more')
expect(requests).toEqual(window >= 128_000 ? ['chat', 'summary', 'chat'] : ['chat', 'chat'])
expect(notifications.mock.calls).toEqual(window >= 128_000 ? [[true], [false]] : [])
expect(agent.state.messages.at(-1)).toMatchObject({ stopReason: 'stop' })
},
)

it.each(['failure', 'stop'])(
'ends between-turn compaction notifications after a %s',
async outcome => {
const notifications: boolean[] = []
const fetchModel = vi
.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(reply('x'.repeat(150_000), 120_000))
vi.spyOn(console, 'error').mockImplementation(vi.fn())
const agent = createReaderAgent(config, localTools(), {
...session,
model: { ...session.model, contextWindow: 128_000 },
onCompactionChange: compacting => {
notifications.push(compacting)
if (compacting && outcome === 'stop') agent.abort()
},
})
await agent.prompt('Earlier question')
let chats = 0
fetchModel.mockImplementation(async (_url, init) => {
if (String(init?.body).includes('context summarization assistant'))
return Response.json({ error: { message: 'Unavailable' } }, { status: 503 })
chats += 1
return chats === 1 ? call('get_reader_state', {}) : reply('Finished')
})
await agent.prompt('Read more')
expect(notifications).toEqual([true, false])
expect(conversationMessages(agent).some(message => message.role === 'compaction')).toBe(false)
expect(chats).toBe(outcome === 'stop' ? 1 : 2)
expect(agent.state.messages.at(-1)).toMatchObject({
stopReason: outcome === 'stop' ? 'aborted' : 'stop',
})
},
)

it('restores the transcript under the selected conversation id', () => {
const message = createReaderUserMessage('Earlier question', [])
const agent = createReaderAgent(config, localTools(), {
Expand Down
27 changes: 26 additions & 1 deletion ui-packages/web/src/features/assistant/create-reader-agent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Agent, type AgentMessage, type AgentState } from '@earendil-works/pi-agent-core'
import { projectContext } from '../../core/agent/compaction'
import { needsCompaction, projectContext } from '../../core/agent/compaction'
import { type AgentDefinition, assemble, type Skill, streamFn } from '../../core/agent/definition'
import { LocalToolError } from '../../core/agent/tool'
import {
Expand All @@ -11,6 +11,7 @@ import { type ModelRuntime, visionModelFor } from '../../core/models/model-runti
import { getStoredFile, listStoredFiles } from '../../data/file-store'
import { markdownText } from '../../formats/markdown-text'
import { memoryAgentParts } from '../memory'
import { compactConversation } from './compaction'
import { createDocumentTools, type DocumentAccess } from './document-tools'
import { createDocxRuntime, type DocxRuntime } from './docx/runtime'
import { createImageTools } from './image-tools'
Expand Down Expand Up @@ -110,6 +111,27 @@ const readerAgent: AgentDefinition<ReaderContext> = {
export const conversationMessages = (agent: Agent) =>
agent.state.messages.filter(message => message.role !== 'system')

// A reply that reads page after page can pass the threshold between two of its own requests. The
// summary joins the transcript before the next one; a failure leaves the reply to go on without it.
const compactBetweenTurns = async (
agent: Agent,
signal?: AbortSignal,
onCompactionChange?: (compacting: boolean) => void,
) => {
const { model } = agent.state
if (!needsCompaction(agent.state.messages, model.contextWindow)) return undefined
onCompactionChange?.(true)
try {
const message = await compactConversation(model, conversationMessages(agent), signal)
return message && !signal?.aborted ? { messages: [message] } : undefined
} catch (cause) {
if (!signal?.aborted) console.error('Unable to compact the conversation between turns', cause)
return undefined
} finally {
onCompactionChange?.(false)
}
}

export const createReaderAgent = (
runtime: ModelRuntime,
local: LocalTools,
Expand All @@ -118,6 +140,7 @@ export const createReaderAgent = (
messages: readonly AgentMessage[]
// Read at each call, so turning web search on or off needs no new agent.
web?: () => WebState
onCompactionChange?: (compacting: boolean) => void
} & Pick<AgentState, 'model' | 'thinkingLevel'>,
) => {
const pdf = createPdfRuntime(getStoredFile)
Expand Down Expand Up @@ -151,6 +174,8 @@ export const createReaderAgent = (
const projected = projectContext(messages)
return memory ? memory.transformContext(projected) : projected
},
prepareNextTurnWithContext: (_turn, signal) =>
compactBetweenTurns(agent, signal, session.onCompactionChange),
streamFn,
})
agent.subscribe(async event => {
Expand Down
5 changes: 3 additions & 2 deletions ui-packages/web/src/features/conversation/composer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,13 @@ export const ConversationComposer = ({
const value = draft || command
const matches = command ? matchCommands(command, commands) : []
const menuOpen = !dismissed && matches.length > 0
const running = phase === 'running' || phase === 'stopping'
// A summary can be stopped like a reply, but accepts no new messages.
const running = phase === 'running' || phase === 'stopping' || phase === 'compacting'
const readyAttachments = attachments.filter(item => item.status === 'ready')
const hasUnavailable = readyAttachments.some(item => !availableFileIds.has(item.metadata.id))
// While a reply runs, sending queues the message.
const canSend =
(phase === 'ready' || running) &&
(phase === 'ready' || phase === 'running') &&
!unsettled &&
!hasUnavailable &&
Boolean(value.trim() || readyAttachments.length)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,12 @@ export const attachAgent = (
: getActive(ctx).webSearch
? 'on'
: 'off',
onCompactionChange: compacting => {
if (runtime.agent !== agent || runtime.switching) return
const { phase } = store.getState()
if (compacting && phase === 'running') store.setState({ phase: 'compacting' })
if (!compacting && phase === 'compacting') store.setState({ phase: 'running' })
},
})
agent.state.tools = withWebSearch(
agent.state.tools,
Expand Down
Loading