Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(agent): drop image attachments for models that cannot read images (#16816)

Mo AbuAboud43a3e43f46cc
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.md
index 67aed13151a..f9a508e28cd 100644
--- a/brain/knowledge/ai-intelligence/ai-agents.md
+++ b/brain/knowledge/ai-intelligence/ai-agents.md
@@ -30,6 +30,7 @@ Three things follow. `run_agent` has two modes: pointed at a saved agent (`agent
- **PredefinedInputsStructure** — per-field `AGENT_DECIDE` / `CHOOSE_YOURSELF` / `LEAVE_EMPTY` baked into the tool so the agent knows which inputs it controls.
### Gotchas
+- **Chat image attachments must be gated on the model's `supportsVision`, not just the provider.** The managed key serves the whole OpenRouter catalogue, including text-only models like `z-ai/glm-5.3`. Sending them an image part gets a `404 No endpoints found that support image input`, which the classifier counts as `internal` on the managed key, so it pages. The image is saved in `conversation.messages`, so every later turn in that conversation fails too. `dropImagesForTextOnlyModels` (`ee/agent/agent-file-utils.ts`) replaces image parts in the payload sent to the LLM with a note telling the model it cannot see the image, in `getAgentConfig`, when any model that reads the conversation (the run candidates, plus the fast model outside chat) is catalogued `supportsVision: false`. Saved history keeps the image.
- **A chat stores its own model pick, and a chat saved before that pins its key on its next turn.** `agent_conversation` holds a tier (`modelTierId`) or a key + model (`providerConfigId` + `modelName`); a Credits pick is the managed row id plus a credits tier id. A row with only `modelName` (old web client, or any chat from before 0.93.0) runs on today's Default-AI-key path once, then `agentChatModel.legacyPin` stores the key and the model it resolved to. A published tier slug (`fast`/`smart`/`premium`) stays a slug on every key, or an own-key `premium` chat would think at the default budget from turn 2; an unknown slash-free name on an Activepieces/OpenRouter key stores the tier that actually ran, because the pinned path has no fallback. The pin is saved under a `FOR SHARE` lock on the key row and only if the key still serves the chat, and key delete removes the row before it unpins, so a key deleted mid-turn is never pinned. The write is conditional on the row still being unpinned, so a model change made during the turn wins. A chat with nothing stored gets the Default tier, else the Default AI key path, else the picker's first option, and stores it.
- **Only a pinned chat fails on an unknown model.** A pinned pick whose model or key went away fails with "The model this chat uses isn't available anymore" (S11). A legacy row keeps the old silent fallback (`curated[0]` / default tier), so an upgrade never breaks a chat. Deleting a key, or narrowing its projects or models, unpins the chats it no longer serves (`aiUsageHooks.unpinConversationsFromKey`), and they re-pin on the next turn. The worker's `modelName` write-back skips pinned rows: it sends the tier slug back, which would replace a real model id. A chat run reads its model and key from the freshly loaded conversation, never from the job's `modelName`: the job carries the model from enqueue time, and a pick changed while the message waited would pair an old model with a new key. Billing labels a turn by the worker's `answeredBy` (sent on every turn), not by the conversation's current pick, which can change mid-turn. A pinned Activepieces/OpenRouter tier slug never falls back: an unpublished slug, or one whose model the key's `modelIds` excludes, fails with S11. A key pick needs a chat with a project: the offer check (`aiModelOptionsService.list`) is per project, and the run path passes own-key names straight through.
diff --git a/packages/server/api/src/app/ee/agent/agent-file-utils.ts b/packages/server/api/src/app/ee/agent/agent-file-utils.ts
index 49ce724ecdb..592bb644259 100644
--- a/packages/server/api/src/app/ee/agent/agent-file-utils.ts
+++ b/packages/server/api/src/app/ee/agent/agent-file-utils.ts
@@ -1,6 +1,6 @@
import { ActivepiecesError, ErrorCode, isNil } from '@activepieces/core-utils'
-import { CHAT_ALLOWED_MIME_TYPES, FileCompression, FileType } from '@activepieces/shared'
-import { UserContent } from 'ai'
+import { AIProviderModelMetadata, CHAT_ALLOWED_MIME_TYPES, FileCompression, FileType } from '@activepieces/shared'
+import { ModelMessage, UserContent } from 'ai'
import { FastifyBaseLogger } from 'fastify'
import { fileService, GetDataResponse } from '../../file/file.service'
@@ -10,6 +10,8 @@ const TEXT_MIME_TYPES = new Set<string>(
const MAX_EXTRACTED_TEXT_LENGTH = 50_000
+const UNREADABLE_IMAGE_NOTE = '[The user attached an image here, but the current model cannot read images, so it was not sent. Do not guess its contents. Tell the user to switch to a model that supports images if they need it read.]'
+
async function extractPdfText(base64Data: string): Promise<string> {
const { extractText, getDocumentProxy } = await import('unpdf')
const buffer = Buffer.from(base64Data, 'base64')
@@ -108,4 +110,21 @@ async function readConversationFile({ platformId, conversationId, accessibleProj
return fileService(log).getDataOrThrow({ projectId: file.projectId ?? undefined, fileId, type: FileType.FLOW_STEP_FILE })
}
-export { buildUserContentWithFiles, persistAgentAttachments, buildAttachmentNote, readConversationFile }
+function dropImagesForTextOnlyModels({ messages, models }: {
+ messages: ModelMessage[]
+ models: Array<AIProviderModelMetadata | undefined>
+}): ModelMessage[] {
+ const someModelIsTextOnly = models.some((model) => model?.supportsVision === false)
+ if (!someModelIsTextOnly) {
+ return messages
+ }
+ return messages.map((message) => message.role === 'user' && Array.isArray(message.content)
+ ? { ...message, content: message.content.map((part) => isImagePart(part) ? { type: 'text' as const, text: UNREADABLE_IMAGE_NOTE } : part) }
+ : message)
+}
+
+function isImagePart(part: Exclude<UserContent, string>[number]): boolean {
+ return part.type === 'image' || (part.type === 'file' && part.mediaType.startsWith('image/'))
+}
+
+export { buildUserContentWithFiles, persistAgentAttachments, buildAttachmentNote, readConversationFile, dropImagesForTextOnlyModels }
diff --git a/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts
index d6d537a1e75..bbb06d8d2ea 100644
--- a/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts
+++ b/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts
@@ -1,12 +1,12 @@
import { ActivepiecesError, AIProviderName, ErrorCode, isFallbackWorthy, isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
-import { agentAiUtils, aiProviderSignal, aiUtils } from '@activepieces/server-utils'
+import { agentAiUtils, aiProviderSignal, aiUtils, modelCatalog } from '@activepieces/server-utils'
import { AgentConfigResponse, AgentConversation, AgentRunSource, aiProviderUtils, GetAgentConfigRequest, GetEnabledAiToolsResponse, GetProviderConfigResponse, PersistedAgentMessage, PersistedAgentPartType, PersistedAgentRole } from '@activepieces/shared'
import { LanguageModel, ModelMessage, UserContent } from 'ai'
import { FastifyBaseLogger } from 'fastify'
import { agentApprovalGate } from '.././agent-approval-gate'
import { agentChatModel } from '.././agent-chat-model'
import { agentCompaction } from '.././agent-compaction'
-import { buildAttachmentNote, buildUserContentWithFiles, persistAgentAttachments } from '.././agent-file-utils'
+import { buildAttachmentNote, buildUserContentWithFiles, dropImagesForTextOnlyModels, persistAgentAttachments } from '.././agent-file-utils'
import { agentHelpers } from '.././agent-helpers'
import { agentModelTier, agentTierCandidates, AgentTierRun } from '.././agent-model-tier'
import { agentMcp } from '.././mcp/agent-mcp'
@@ -242,7 +242,15 @@ export const agentConfigRpc = (log: FastifyBaseLogger) => ({
const onboardingNote = agentSurfaceNotes.onboardingNote({ source: conversation.source, ...spreadIfDefined('messageSource', input.messageSource) })
const newUserMessage: ModelMessage = { role: 'user' as const, content: isNil(onboardingNote) ? userContent : withLeadingNote({ content: userContent, note: onboardingNote }) }
const allMessages = [...previousMessages, newUserMessage]
- const llmHistory = agentAiUtils.collapseStaleToolOutputs({ messages: allMessages })
+ const fastModelSeesMessages = conversation.source !== AgentRunSource.CHAT
+ const modelsSeeingMessages = isNil(tierRun)
+ ? [resolvedModelId, ...(fastModelSeesMessages ? [fastModelId] : [])].map((modelId) => ({ provider: providerConfig.provider, modelId }))
+ : [...tierRun.candidates, ...(fastModelSeesMessages && !isNil(tierRun.fast) ? [tierRun.fast] : [])].map((candidate) => ({ provider: candidate.config.provider, modelId: candidate.modelId }))
+ const catalog = await modelCatalog.load()
+ const llmHistory = dropImagesForTextOnlyModels({
+ messages: agentAiUtils.collapseStaleToolOutputs({ messages: allMessages }),
+ models: modelsSeeingMessages.map((model) => catalog.lookup(model)),
+ })
const previousUiMessages = (conversation.uiMessages ?? []) as PersistedAgentMessage[]
const uiMessagesWithUser: PersistedAgentMessage[] = [
diff --git a/packages/server/api/test/unit/app/ee/agent/agent-file-utils.test.ts b/packages/server/api/test/unit/app/ee/agent/agent-file-utils.test.ts
new file mode 100644
index 00000000000..5f1f71575ea
--- /dev/null
+++ b/packages/server/api/test/unit/app/ee/agent/agent-file-utils.test.ts
@@ -0,0 +1,26 @@
+import { ModelMessage } from 'ai'
+import { describe, expect, it } from 'vitest'
+import { buildUserContentWithFiles, dropImagesForTextOnlyModels } from '../../../../../src/app/ee/agent/agent-file-utils'
+
+describe('dropImagesForTextOnlyModels', () => {
+ const imageTurn = async (): Promise<ModelMessage[]> => [
+ { role: 'user', content: await buildUserContentWithFiles({ text: 'what is in this screenshot?', files: [{ name: 'shot.png', mimeType: 'image/png', data: 'aGVsbG8=' }] }) },
+ { role: 'assistant', content: 'A login page.' },
+ ]
+
+ it('replaces the image with a note when the model cannot read images, so the provider does not 404 the turn', async () => {
+ const messages = dropImagesForTextOnlyModels({ messages: await imageTurn(), models: [{ supportsVision: false }, { supportsVision: true }] })
+
+ expect(messages[0].content).toEqual([
+ { type: 'text', text: 'what is in this screenshot?' },
+ { type: 'text', text: expect.stringContaining('cannot read images') },
+ ])
+ expect(messages[1]).toEqual({ role: 'assistant', content: 'A login page.' })
+ })
+
+ it('keeps the image for vision models and for models the catalog does not know', async () => {
+ const original = await imageTurn()
+
+ expect(dropImagesForTextOnlyModels({ messages: original, models: [{ supportsVision: true }, undefined] })).toEqual(original)
+ })
+})