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
3 changes: 2 additions & 1 deletion ui-packages/web/src/core/byok/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ const customModel = (id: string, provider: string, baseUrl: string): Model<Api>
// table and the reader names the model that handles them.
input: ['text', 'image'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 128_000,
// Unknown. Pi reads 0 as no known window, rather than capping replies against a guessed one.
contextWindow: 0,
maxTokens: 4_096,
})

Expand Down
9 changes: 6 additions & 3 deletions ui-packages/web/src/features/agent/image-tools.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Type } from '@earendil-works/pi-ai'
import { prepareImage, readerImagePixels } from '../../core/image-input'
import type { getStoredFile } from '../../data/file-store'
import { bind } from './tool'
import { bind, Metered } from './tool'
import { LocalToolError } from './tool-types'
import type { VisionAnalyzer } from './vision'

Expand All @@ -25,12 +25,15 @@ export const createImageTools = (loadFile: typeof getStoredFile, analyze: Vision
readerImagePixels,
signal,
)
const analysis = await analyze(
const { analysis, usage } = await analyze(
image,
input.question?.trim() || 'Describe this image and transcribe any important visible text.',
signal,
)
return { fileId: stored.metadata.id, path: stored.metadata.path, analysis }
return new Metered(
{ fileId: stored.metadata.id, path: stored.metadata.path, analysis },
usage,
)
},
),
]
13 changes: 9 additions & 4 deletions ui-packages/web/src/features/agent/pdf/tools.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Type } from '@earendil-works/pi-ai'
import { documentPagePixels, prepareImage } from '../../../core/image-input'
import { bind } from '../tool'
import { bind, Metered } from '../tool'
import { LocalToolError } from '../tool-types'
import type { VisionAnalyzer } from '../vision'
import type { PdfRuntime } from './runtime'
Expand Down Expand Up @@ -32,13 +32,18 @@ export const createPdfTools = (pdf: PdfRuntime, analyze?: VisionAnalyzer) => {
pageNumber: Type.Integer({ minimum: 1 }),
question: Type.String({ minLength: 1, maxLength: 2000 }),
}),
async (input, signal): Promise<AnalyzePdfPageResult> => {
async (input, signal) => {
if (!input.question.trim())
throw new LocalToolError('Provide a focused question for the PDF page.')
const blob = await pdf.renderPage(input.fileId, input.pageNumber, signal)
const image = await prepareImage(blob, blob.type, documentPagePixels, signal)
const analysis = await analyze(image, input.question, signal)
return { fileId: input.fileId, pageNumber: input.pageNumber, analysis }
const { analysis, usage } = await analyze(image, input.question, signal)
const result: AnalyzePdfPageResult = {
fileId: input.fileId,
pageNumber: input.pageNumber,
analysis,
}
return new Metered(result, usage)
},
),
]
Expand Down
21 changes: 18 additions & 3 deletions ui-packages/web/src/features/agent/tool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import type { AgentTool } from '@earendil-works/pi-agent-core'
import type { Static, TSchema } from '@earendil-works/pi-ai'
import type { Static, TSchema, Usage } from '@earendil-works/pi-ai'

// A tool that calls a model itself returns that call's usage beside its result. Pi keeps it on the
// tool result, apart from the context the model sees.
export class Metered {
constructor(
readonly result: unknown,
readonly usage: Usage,
) {}
}

export const bind = <P extends TSchema>(
name: string,
description: string,
Expand All @@ -13,8 +23,13 @@ export const bind = <P extends TSchema>(
executionMode: 'sequential',
execute: async (_id, input, signal) => {
signal?.throwIfAborted()
const result = await execute(input, signal)
const output = await execute(input, signal)
signal?.throwIfAborted()
return { content: [{ type: 'text', text: JSON.stringify(result) }], details: undefined }
const result = output instanceof Metered ? output.result : output
return {
content: [{ type: 'text', text: JSON.stringify(result) }],
details: undefined,
...(output instanceof Metered && { usage: output.usage }),
}
},
})
6 changes: 3 additions & 3 deletions ui-packages/web/src/features/agent/vision.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type Api, clampThinkingLevel, type Model } from '@earendil-works/pi-ai'
import { type Api, clampThinkingLevel, type Model, type Usage } from '@earendil-works/pi-ai'
import type { PreparedImage } from '../../core/image-input'
import { apiKeyFor, models, proxyRequestOptions } from './model-runtime'

Expand All @@ -8,7 +8,7 @@ export type VisionAnalyzer = (
image: PreparedImage,
question: string,
signal?: AbortSignal,
) => Promise<string>
) => Promise<{ analysis: string; usage: Usage }>

export const createVisionAnalyzer = (model: Model<Api>): VisionAnalyzer => {
const thinkingLevel = clampThinkingLevel(model, 'off')
Expand Down Expand Up @@ -43,6 +43,6 @@ export const createVisionAnalyzer = (model: Model<Api>): VisionAnalyzer => {
.join('')
.trim()
if (!analysis) throw new Error('The vision model returned no image analysis.')
return analysis
return { analysis, usage: response.usage }
}
}
151 changes: 80 additions & 71 deletions ui-packages/web/src/features/conversation/composer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import type { ConversationDraft } from '../../../core/conversations'
import { DraftAttachmentTray } from '../conversation-attachments'
import { ConversationModelControl, type ModelControlProps } from '../model-control'
import type { ConversationTokenUsage } from '../token-usage'
import type { ConversationPhase } from '../use-conversation'
import type { DraftAttachment } from '../use-draft-attachments'
import { QueuedMessages } from './queued-messages'
Expand All @@ -22,12 +23,14 @@ import {
SlashCommandMenu,
} from './slash-command-menu'
import styles from './style.module.scss'
import { TokenUsageStatus } from './token-usage-status'

type ComposerProps = {
modelConfiguration: Pick<ModelControlProps, 'providers' | 'selection'> | null
onModelChange: ModelControlProps['onModelChange']
onEffortChange: ModelControlProps['onEffortChange']
onConfigureModels: ModelControlProps['onConfigure']
tokenUsage: ConversationTokenUsage | null
inputRef: RefObject<HTMLTextAreaElement | null>
draft: string
phase: ConversationPhase
Expand Down Expand Up @@ -58,6 +61,7 @@ export const ConversationComposer = ({
onModelChange,
onEffortChange,
onConfigureModels,
tokenUsage,
draft,
phase,
queued,
Expand Down Expand Up @@ -179,52 +183,81 @@ export const ConversationComposer = ({
}}
onDrop={addDroppedFiles}
>
<QueuedMessages queued={queued} onRemove={onRemoveQueued} />
<DraftAttachmentTray
attachments={attachments}
onOpen={onOpenFile}
onRetry={onRetry}
onRemove={onRemove}
availableFileIds={availableFileIds}
/>
{menuOpen && (
<SlashCommandMenu id={menuId} commands={matches} selected={selected} onRun={runCommand} />
)}
<textarea
ref={inputRef}
disabled={phase === 'loading' || phase === 'switching'}
aria-label="Your question"
placeholder="Ask about what you are reading, / for commands"
aria-controls={menuOpen ? menuId : undefined}
aria-activedescendant={menuOpen ? commandOptionId(menuId, selected) : undefined}
value={value}
onChange={event => {
resizeTextarea(event.currentTarget)
changeText(event.target.value)
}}
onPaste={event => {
const files = Array.from(event.clipboardData.files)
if (!files.length) return
event.preventDefault()
onAdd(files)
}}
rows={1}
onKeyDown={event => {
if (event.nativeEvent.isComposing || event.keyCode === 229) return
if (menuOpen && !event.shiftKey && handleMenuKey(event.key)) {
event.preventDefault()
return
}
if (event.key === 'Escape' && running) {
event.preventDefault()
onStop()
return
}
if (event.key !== 'Enter' || event.shiftKey) return
event.preventDefault()
submit()
}}
/>
<div className={styles.box}>
<QueuedMessages queued={queued} onRemove={onRemoveQueued} />
<DraftAttachmentTray
attachments={attachments}
onOpen={onOpenFile}
onRetry={onRetry}
onRemove={onRemove}
availableFileIds={availableFileIds}
/>
{menuOpen && (
<SlashCommandMenu id={menuId} commands={matches} selected={selected} onRun={runCommand} />
)}
<div className={styles.input}>
<textarea
ref={inputRef}
disabled={phase === 'loading' || phase === 'switching'}
aria-label="Your question"
placeholder="Ask about what you are reading, / for commands"
aria-controls={menuOpen ? menuId : undefined}
aria-activedescendant={menuOpen ? commandOptionId(menuId, selected) : undefined}
value={value}
onChange={event => {
resizeTextarea(event.currentTarget)
changeText(event.target.value)
}}
onPaste={event => {
const files = Array.from(event.clipboardData.files)
if (!files.length) return
event.preventDefault()
onAdd(files)
}}
rows={1}
onKeyDown={event => {
if (event.nativeEvent.isComposing || event.keyCode === 229) return
if (menuOpen && !event.shiftKey && handleMenuKey(event.key)) {
event.preventDefault()
return
}
if (event.key === 'Escape' && running) {
event.preventDefault()
onStop()
return
}
if (event.key !== 'Enter' || event.shiftKey) return
event.preventDefault()
submit()
}}
/>
{running && (
<button
type="button"
className={styles.sendButton}
aria-label="Stop generation"
title="Stop generation"
disabled={phase === 'stopping'}
onClick={onStop}
>
<Square size={13} />
</button>
)}
{(!running || canSend) && (
<button
type="button"
className={styles.sendButton}
aria-label={running ? 'Queue message' : 'Send question'}
title={running ? 'Queue message' : 'Send question'}
disabled={!canSend}
onClick={submit}
>
<ArrowUp size={17} />
</button>
)}
</div>
{dragging && <span className={styles.dropHint}>Drop files to attach</span>}
</div>
<div className={styles.bottom}>
<button
type="button"
Expand Down Expand Up @@ -257,32 +290,8 @@ export const ConversationComposer = ({
/>
)}
{limitReached && <span className={styles.attachmentLimit}>10 attachments maximum</span>}
{running && (
<button
type="button"
className={styles.sendButton}
aria-label="Stop generation"
title="Stop generation"
disabled={phase === 'stopping'}
onClick={onStop}
>
<Square size={13} />
</button>
)}
{(!running || canSend) && (
<button
type="button"
className={styles.sendButton}
aria-label={running ? 'Queue message' : 'Send question'}
title={running ? 'Queue message' : 'Send question'}
disabled={!canSend}
onClick={submit}
>
<ArrowUp size={17} />
</button>
)}
{tokenUsage && <TokenUsageStatus usage={tokenUsage} />}
</div>
{dragging && <span className={styles.dropHint}>Drop files to attach</span>}
</fieldset>
)
}
Loading