feat(agent): enable read_asset tool for autofill agent (#396)

* feat(agent): enable read_asset tool for autofill agent

* fix(transcode): trigger autofill task for pdf assets

* fix(transcode): allow autofill task creation on all file assets

* fix(agent): require targetAssetId and teamId for autofill read_asset authorization

* feat(agent): instruct autofill agent to report failure directly if read_asset fails
This commit is contained in:
Yiling-J
2026-09-08 14:19:03 +08:00
committed by GitHub
parent 3a05332cd6
commit 04fd571bd9
10 changed files with 548 additions and 144 deletions
+84 -2
View File
@@ -472,6 +472,82 @@ describe('Agent Activities', () => {
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
let capturedSystemPrompt = ''
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => {
const params = config as {
systemPrompt?: string
customTools: Array<{
name: string
execute: (id: string, args: Record<string, unknown>) => Promise<unknown>
}>
}
capturedSystemPrompt = params.systemPrompt ?? ''
const tool = params.customTools.find((t) => t.name === 'autofill_metadata')
if (tool) {
await tool.execute('1', { f1: 'val' })
}
return {
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test
harness: mockHarness as unknown as AgentHarness<any, any, any, any>,
}
})
const context = {
agent: {
id: 'b1',
type: 'autofill',
provider: { name: 'google' },
modelRef: { modelId: 'gemini' },
},
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
await autofillAiActivity({
teamId: 't1',
assetId: 'a1',
assetName: 'test.mp4',
mediaType: 'video/mp4',
duration: 30.5,
images: [],
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
context,
})
const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? ''
expect(capturedPrompt).toContain('You are tasked with analyzing the asset "test.mp4"')
expect(capturedPrompt).toContain('Call the "read_asset" tool with assetId: "a1"')
expect(capturedPrompt).toContain(
'Video duration: 30.5s. Recommended inspection: call read_asset with videoConfig: { start: 0, end: 30.5, count: 10 }.',
)
expect(capturedPrompt).toContain(
'call the "autofill_metadata" tool to provide the extracted metadata values.',
)
expect(capturedPrompt).toContain(
'If "read_asset" fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.',
)
expect(capturedPrompt).not.toContain('<context>')
expect(capturedSystemPrompt).toContain(
"If 'read_asset' fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.",
)
})
it('should include PDF page count recommendations in autofill prompt when present', async () => {
const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: 'Captured' }],
usage: { input: 5, output: 5 },
}),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => {
const params = config as {
customTools: Array<{
@@ -499,14 +575,20 @@ describe('Agent Activities', () => {
await autofillAiActivity({
teamId: 't1',
assetId: 'pdf-1',
assetName: 'report.pdf',
mediaType: 'application/pdf',
pageCount: 15,
images: [],
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
context,
})
const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? ''
expect(capturedPrompt).toContain('Analyze the provided images and extract metadata.')
expect(capturedPrompt).not.toContain('<context>')
expect(capturedPrompt).toContain('You are tasked with analyzing the asset "report.pdf"')
expect(capturedPrompt).toContain(
'Document pages: 15. Recommended inspection: call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: 15 } or mode: "text".',
)
})
})
+36 -5
View File
@@ -178,6 +178,10 @@ User messages may contain a <context> block detailing the user, active asset loc
systemPrompt += `\n\n# Comment Threads\nWhen operating in comment mode, previous top-level messages in the conversation history may contain a <thread id="..." reply_count="..." /> tag indicating an earlier discussion thread with replies. If a user's question refers to or depends on earlier comments or discussions, you can use the 'read_thread' tool with the thread ID to inspect all replies in that thread.`
}
if (agent.type === 'autofill') {
systemPrompt += `\n\n# Autofill Instructions\nWhen performing metadata autofill, inspect the asset content using the 'read_asset' tool. If 'read_asset' fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.`
}
const agentConfig = agent.config as PrismaJson.AgentConfig | null | undefined
const thinkingLevel = agentConfig?.thinkingLevel || 'off'
@@ -210,6 +214,7 @@ User messages may contain a <context> block detailing the user, active asset loc
sessionId: params.sessionId,
userId: params.userId,
projectId: params.projectId,
assetId: params.assetId,
userCommentId: params.userCommentId,
customTools: [...(params.tools || []), ...mcpTools],
providers: dbProviders.map((p) => ({
@@ -522,22 +527,25 @@ export async function agentChatActivity(params: AgentChatParams) {
export interface AutofillAiParams {
teamId: string
images: string[]
images?: string[]
fields: AutofillField[]
context: AgentExecutionContext
assetId?: string
projectId?: string
assetName?: string
mediaType?: string
duration?: number
pageCount?: number
}
export async function autofillAiActivity(params: AutofillAiParams) {
const prompt = 'Analyze the provided images and extract metadata.'
const toolSchema = fieldsToTypeBoxSchema(params.fields)
let capturedData: Record<string, unknown> | null = null
const autofillTool: AgentTool = {
name: 'autofill_metadata',
label: 'Autofill Metadata',
description: 'Extract metadata from the images.',
description: 'Provide the extracted metadata once you have analyzed the asset content.',
parameters: toolSchema,
execute: async (_toolCallId, toolParams) => {
capturedData = toolParams as Record<string, unknown>
@@ -548,7 +556,30 @@ export async function autofillAiActivity(params: AutofillAiParams) {
},
}
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
const promptLines: string[] = [
`You are tasked with analyzing the asset "${params.assetName || params.assetId || 'unknown'}" (ID: "${params.assetId || ''}", mediaType: "${params.mediaType || 'unknown'}") to extract and autofill its metadata fields.`,
]
if (params.duration !== undefined && params.duration > 0) {
promptLines.push(
`- Video duration: ${params.duration.toFixed(1)}s. Recommended inspection: call read_asset with videoConfig: { start: 0, end: ${params.duration.toFixed(1)}, count: 10 }.`,
)
}
if (params.pageCount !== undefined && params.pageCount > 0) {
promptLines.push(
`- Document pages: ${params.pageCount}. Recommended inspection: call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: ${Math.min(params.pageCount, 20)} } or mode: "text".`,
)
}
promptLines.push(
'',
'Instructions:',
`1. Call the "read_asset" tool with assetId: "${params.assetId || ''}" to inspect the asset content (use imageConfig, videoConfig, or docConfig according to the media type).`,
'2. After analyzing the retrieved content, call the "autofill_metadata" tool to provide the extracted metadata values.',
'3. If "read_asset" fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.',
)
const fullPrompt = promptLines.join('\n')
const { agent } = params.context
@@ -556,7 +587,7 @@ export async function autofillAiActivity(params: AutofillAiParams) {
teamId: params.teamId,
agentId: agent.id,
prompt: fullPrompt,
images: params.images,
images: params.images || [],
sessionId: undefined,
userId: undefined,
projectId: params.projectId,