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(knowledge-base): uploaded files can now be searched by agents (#15930)

Hazem Adel914c47f4f174
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.md
index ec2b81cd1c1..1bd7ebe3813 100644
--- a/brain/knowledge/ai-intelligence/ai-agents.md
+++ b/brain/knowledge/ai-intelligence/ai-agents.md
@@ -97,7 +97,7 @@ Paths verified 2026-07-17. An earlier version pointed at `packages/core/shared/s
### Knowledge base gotchas
-- **A knowledge base uploaded through the UI is not searchable.** Nothing in the upload path generates chunk embeddings; `knowledge-base.controller.ts` only *accepts* an embedding on a chunk. Chunks land with `embedding IS NULL`, and search filters those out, so the result is an empty answer rather than an error.
+- **An upload is embedded when it arrives, or refused.** `knowledgeBaseService.uploadFile` chunks and embeds the file in memory before writing anything, then saves the blob and writes the file record and its chunks in one transaction (the blob is deleted if that fails). It refuses with `KNOWLEDGE_BASE_NEEDS_AI_PROVIDER` when the project has no chat provider and `KNOWLEDGE_BASE_FILE_HAS_NO_TEXT` when nothing searchable comes out; the upload dialog maps both to translated messages. Embeddings bill like any other managed-provider call. Files uploaded before this fix are indexed on the agent's first search of them (`embedMissingChunks`, run only from the agent's knowledge-base tool, never from the read-only `/search` route). If that fails, the agent says the file could not be indexed, and uploading it again shows why.
- **`knowledge_base_chunk` is created by a migration that records itself as run even when pgvector is absent.** A database that gains pgvector later never gets the table, because the migration is already marked complete. Deleting its row from `migrations` replays it safely, since the DDL is `CREATE TABLE IF NOT EXISTS`.
- **Embeddings are stored at a fixed 768 dimensions, and most models do not return that.** `text-embedding-3-small` answers 1536, and the `dimensions` provider option is namespaced under `openai`, so the OpenRouter and managed paths never see it. `aiUtils.toStorageEmbedding` truncates and re-normalises instead, which is what the option does server-side and works whatever the provider returns. This only holds for Matryoshka-trained models — adding a model that is not one will truncate badly and silently.
diff --git a/brain/knowledge/data-storage-observability/knowledge-base.md b/brain/knowledge/data-storage-observability/knowledge-base.md
index 44d6bf9541c..8119aaf3638 100644
--- a/brain/knowledge/data-storage-observability/knowledge-base.md
+++ b/brain/knowledge/data-storage-observability/knowledge-base.md
@@ -24,7 +24,7 @@ A project-scoped document store: users upload PDF/DOCX/TXT/CSV files, which are
- Allowed MIME types (`KB_ALLOWED_MIME_TYPES`): PDF, plain text, CSV, DOCX only.
- **`chunkIndex` is a place in the file, and one place holds one row.** `storeChunks` resolves every submitted chunk to an index before it writes anything. An id moves that row to the index and displaces whoever was sitting there. No id takes over the row already at that index, which is what keeps a chunk id stable when a file is indexed again. A repeated index keeps the last copy. A repeated id, or one naming no chunk of this file, is refused rather than guessed at. All of it runs in one transaction behind a `pessimistic_write` lock on the *file* row. Thirteen review rounds on this endpoint were the same bug in different payloads, so add a case to `knowledge-base-storage.test.ts` instead of a branch to the service.
- **Nothing in the database enforces one row per place.** There is no unique index on `(knowledgeBaseFileId, chunkIndex)`, so two writes arriving at once are held apart by that row lock alone, and the lock is a no-op on PGLite because it runs a single connection. The index ships with the indexing work.
-- **Uploaded knowledge is not searchable yet.** Upload stores chunks with no embedding, `search` skips any chunk whose embedding is null, and `ingestFile`, the only thing that embeds, has no callers. `isSearchable` exists so an agent tells the reader the file was never indexed, instead of reporting that the document does not mention what they asked about after reading none of it.
+- **Uploads are embedded when they arrive; older files are embedded on the agent's first search.** `uploadFile` embeds before writing and refuses a file it cannot index. Files from before that change get their missing embeddings from `embedMissingChunks`, which only the agent's knowledge-base tool calls, because the `/search` route is open to read-only members and indexing is a paid write. `isSearchable` still guards the search, so an agent says a file could not be indexed instead of reporting that it does not mention what was asked.
### Key files
Entry point: `knowledgeBaseModule`, registered in `packages/server/api/src/app/app.ts`.
diff --git a/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts
index 4bd6a9514df..d1bac09ef71 100644
--- a/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts
+++ b/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts
@@ -71,12 +71,7 @@ export const toolExecutionRpc = (log: FastifyBaseLogger) => ({
await markTurnAsHavingRead({ conversationId: input.conversationId, ...spreadIfDefined('runId', input.runId) })
const { projectId, platformId } = conversation
const file = await knowledgeBaseService(log).getFileOrThrow({ projectId, id: input.knowledgeBaseFileId })
- const searchable = await knowledgeBaseService(log).isSearchable({ projectId, knowledgeBaseFileId: input.knowledgeBaseFileId })
- if (!searchable) {
- log.warn({ conversation: { id: input.conversationId }, project: { id: projectId }, knowledgeBaseFile: { id: input.knowledgeBaseFileId } }, '[agentRpc#executeKnowledgeBaseTool] The file has no searchable text, so the search was not run')
- return { result: `"${file.displayName}" is attached but has never been indexed, so its text cannot be searched and you have not read any of it. Tell the user exactly that. Do not say the file does not contain what they asked for, and do not suggest re-uploading it: that will not index it either.` }
- }
- const { model, providerOptions } = await agentHelpers.resolveEmbeddingModel({
+ const embeddingModel = () => agentHelpers.resolveEmbeddingModel({
platformId,
scope: { type: 'project', projectId },
billing: { source: ActivepiecesAiConsumerSource.CHAT, platformId, projectId, conversationId: input.conversationId },
@@ -84,6 +79,20 @@ export const toolExecutionRpc = (log: FastifyBaseLogger) => ({
...spreadIfDefined('provider', input.provider),
...spreadIfDefined('providerConfigId', input.providerConfigId),
})
+ const { error: backfillError } = await tryCatch(() => knowledgeBaseService(log).embedMissingChunks({
+ projectId,
+ knowledgeBaseFileId: input.knowledgeBaseFileId,
+ resolveEmbedFn: async () => knowledgeBaseService(log).embedFnOf(await embeddingModel()),
+ }))
+ if (!isNil(backfillError)) {
+ log.warn({ error: backfillError, project: { id: projectId }, knowledgeBaseFile: { id: input.knowledgeBaseFileId } }, '[agentRpc#executeKnowledgeBaseTool] Could not index the file before searching')
+ }
+ const searchable = await knowledgeBaseService(log).isSearchable({ projectId, knowledgeBaseFileId: input.knowledgeBaseFileId })
+ if (!searchable) {
+ log.warn({ conversation: { id: input.conversationId }, project: { id: projectId }, knowledgeBaseFile: { id: input.knowledgeBaseFileId } }, '[agentRpc#executeKnowledgeBaseTool] The file has no searchable text, so the search was not run')
+ return { result: `"${file.displayName}" is attached but could not be indexed, so its text cannot be searched and you have not read any of it. Tell the user exactly that, and that uploading the file again will say why it cannot be indexed. Do not say the file does not contain what they asked for.` }
+ }
+ const { model, providerOptions } = await embeddingModel()
const { embedding } = await embed({ model, value: input.query, providerOptions })
const results = await knowledgeBaseService(log).search({
projectId,
diff --git a/packages/server/api/src/app/knowledge-base/knowledge-base.controller.ts b/packages/server/api/src/app/knowledge-base/knowledge-base.controller.ts
index 9167fafe763..f906007dbfd 100644
--- a/packages/server/api/src/app/knowledge-base/knowledge-base.controller.ts
+++ b/packages/server/api/src/app/knowledge-base/knowledge-base.controller.ts
@@ -1,12 +1,11 @@
-import { ActivepiecesError, ApMultipartFile, ErrorCode, isMultipartFile, Permission, tryCatch } from '@activepieces/core-utils'
+import { ActivepiecesError, ApMultipartFile, ErrorCode, isMultipartFile, Permission } from '@activepieces/core-utils'
import { EMBEDDING_DIMENSIONS } from '@activepieces/server-utils'
-import { FileCompression, FileType, PrincipalType, SERVICE_KEY_SECURITY_OPENAPI } from '@activepieces/shared'
+import { PrincipalType, SERVICE_KEY_SECURITY_OPENAPI } from '@activepieces/shared'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { StatusCodes } from 'http-status-codes'
import { z } from 'zod'
import { ProjectResourceType } from '../core/security/authorization/common'
import { securityAccess } from '../core/security/authorization/fastify-security'
-import { fileService } from '../file/file.service'
import { attachMultipartFieldsToBody } from '../helper/multipart-body'
import { knowledgeBaseService } from './knowledge-base.service'
@@ -43,38 +42,9 @@ export const knowledgeBaseController: FastifyPluginAsyncZod = async (fastify) =>
})
}
- const savedFile = await fileService(request.log).save({
- projectId: request.projectId,
- data: file.data,
- size: file.data.length,
- type: FileType.KNOWLEDGE_BASE,
- compression: FileCompression.NONE,
- fileName: file.filename,
- })
-
- const kbFile = await knowledgeBaseService(request.log).createFile({
- projectId: request.projectId,
- fileId: savedFile.id,
- displayName,
- })
-
- const { data: chunks, error } = await tryCatch(
- () => knowledgeBaseService(request.log).extractChunks({
- projectId: request.projectId,
- knowledgeBaseFileId: kbFile.id,
- }),
- )
- if (!error && chunks.length > 0) {
- await knowledgeBaseService(request.log).storeChunks({
- projectId: request.projectId,
- knowledgeBaseFileId: kbFile.id,
- chunks: chunks.map((content, i) => ({
- content,
- chunkIndex: i,
- metadata: { chunkIndex: i, totalChunks: chunks.length },
- })),
- })
- }
+ const service = knowledgeBaseService(request.log)
+ const embedFn = await service.embedderFor({ projectId: request.projectId, platformId: request.principal.platform.id })
+ const kbFile = await service.uploadFile({ projectId: request.projectId, data: file.data, fileName: file.filename, displayName, embedFn })
return reply.status(StatusCodes.CREATED).send(kbFile)
})
diff --git a/packages/server/api/src/app/knowledge-base/knowledge-base.service.ts b/packages/server/api/src/app/knowledge-base/knowledge-base.service.ts
index fc7859ce8d3..187e0d77e36 100644
--- a/packages/server/api/src/app/knowledge-base/knowledge-base.service.ts
+++ b/packages/server/api/src/app/knowledge-base/knowledge-base.service.ts
@@ -1,11 +1,16 @@
-import { ActivepiecesError, apId, ErrorCode, isNil, spreadIfDefined } from '@activepieces/core-utils'
-import { KnowledgeBaseFile } from '@activepieces/shared'
+import { ActivepiecesAiConsumerSource, ActivepiecesError, apId, ErrorCode, isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
+import { aiUtils } from '@activepieces/server-utils'
+import { FileCompression, FileType, KnowledgeBaseFile } from '@activepieces/shared'
+import { SharedV3ProviderOptions } from '@ai-sdk/provider'
+import { EmbeddingModel, embedMany } from 'ai'
import { parse as parseCsv } from 'csv-parse/sync'
import { FastifyBaseLogger } from 'fastify'
import { In, IsNull, Not } from 'typeorm'
+import { aiProviderService } from '../ai/ai-provider-service'
import { repoFactory } from '../core/db/repo-factory'
import { transaction } from '../core/db/transaction'
import { databaseConnection } from '../database/database-connection'
+import { distributedLock } from '../database/redis-connections'
import { fileService } from '../file/file.service'
import { KnowledgeBaseChunkEntity } from './knowledge-base-chunk.entity'
import { KnowledgeBaseFileEntity } from './knowledge-base-file.entity'
@@ -16,6 +21,8 @@ const kbChunkRepo = repoFactory(KnowledgeBaseChunkEntity)
const INSERT_BATCH_SIZE = 100
const CHUNK_SIZE_CHARS = 2000
const CHUNK_OVERLAP_CHARS = 200
+const EMBED_BATCH_SIZE = 50
+const KNOWLEDGE_BASE_BILLING_CONVERSATION = 'knowledge-base'
function chunkText(text: string): string[] {
const chunks: string[] = []
@@ -54,6 +61,30 @@ function chunkCsvText(csvText: string): string[] {
return chunks
}
+async function chunksOf({ data, fileName }: { data: Buffer, fileName: string }): Promise<string[]> {
+ if (fileName.toLowerCase().endsWith('.csv')) {
+ return chunkCsvText(data.toString('utf-8'))
+ }
+ return chunkText(await extractTextFromFile(data, fileName))
+}
+
+async function embedAll({ texts, embedFn }: { texts: string[], embedFn: EmbedFn }): Promise<number[][]> {
+ const embeddings: number[][] = []
+ for (let start = 0; start < texts.length; start += EMBED_BATCH_SIZE) {
+ const batch = texts.slice(start, start + EMBED_BATCH_SIZE)
+ const batchEmbeddings = await embedFn(batch)
+ if (batchEmbeddings.length !== batch.length) {
+ throw new Error(`Embedding count mismatch: expected ${batch.length}, got ${batchEmbeddings.length}`)
+ }
+ embeddings.push(...batchEmbeddings)
+ }
+ return embeddings
+}
+
+function toVector(embedding: number[]): string {
+ return `[${embedding.join(',')}]`
+}
+
async function extractTextFromFile(fileBuffer: Buffer, fileName: string): Promise<string> {
const lowerName = (fileName ?? '').toLowerCase()
if (lowerName.endsWith('.pdf')) {
@@ -73,38 +104,113 @@ async function extractTextFromFile(fileBuffer: Buffer, fileName: string): Promis
}
export const knowledgeBaseService = (log: FastifyBaseLogger) => ({
- async ingestFile(params: IngestFileParams): Promise<void> {
- const { projectId, knowledgeBaseFileId, embedFn } = params
+ async uploadFile(params: UploadFileParams): Promise<KnowledgeBaseFile> {
+ const { projectId, data, fileName, displayName, embedFn } = params
+ const texts = (await chunksOf({ data, fileName })).filter((text) => text.trim().length > 0)
+ if (texts.length === 0) {
+ throw new ActivepiecesError({
+ code: ErrorCode.VALIDATION,
+ params: { message: KNOWLEDGE_BASE_FILE_HAS_NO_TEXT },
+ })
+ }
+ const embeddings = await embedAll({ texts, embedFn })
+ const savedFile = await fileService(log).save({
+ projectId,
+ data,
+ size: data.length,
+ type: FileType.KNOWLEDGE_BASE,
+ compression: FileCompression.NONE,
+ fileName,
+ })
+ const { data: kbFile, error } = await tryCatch(() => transaction(async (entityManager) => {
+ const file = await entityManager.getRepository(KnowledgeBaseFileEntity).save({ id: apId(), projectId, fileId: savedFile.id, displayName })
+ const rows = texts.map((content, chunkIndex) => ({
+ id: apId(),
+ projectId,
+ knowledgeBaseFileId: file.id,
+ chunkIndex,
+ content,
+ embedding: toVector(embeddings[chunkIndex]),
+ metadata: { chunkIndex, totalChunks: texts.length },
+ }))
+ for (let start = 0; start < rows.length; start += INSERT_BATCH_SIZE) {
+ await entityManager.getRepository(KnowledgeBaseChunkEntity).insert(rows.slice(start, start + INSERT_BATCH_SIZE))
+ }
+ return file
+ }))
+ if (error) {
+ await fileService(log).delete({ projectId, fileId: savedFile.id })
+ throw error
+ }
+ return kbFile
+ },
- const textChunks = await this.extractChunks({ projectId, knowledgeBaseFileId })
- if (textChunks.length === 0) {
- return
+ async embedderFor(params: { projectId: string, platformId: string }): Promise<EmbedFn> {
+ const { projectId, platformId } = params
+ const provider = await aiProviderService(log).getChatProvider({ platformId, scope: { type: 'project', projectId } })
+ if (isNil(provider)) {
+ throw new ActivepiecesError({
+ code: ErrorCode.VALIDATION,
+ params: { message: KNOWLEDGE_BASE_NEEDS_AI_PROVIDER },
+ })
}
+ const { model, providerOptions } = aiUtils.createEmbeddingModel({
+ credentials: provider,
+ platformId,
+ providerConfigId: provider.configId,
+ billing: { source: ActivepiecesAiConsumerSource.CHAT, platformId, projectId, conversationId: KNOWLEDGE_BASE_BILLING_CONVERSATION },
+ })
+ return this.embedFnOf({ model, providerOptions })
+ },
- const EMBED_BATCH_SIZE = 50
- const allChunks: StoreChunksParams['chunks'] = []
- for (let i = 0; i < textChunks.length; i += EMBED_BATCH_SIZE) {
- const batch = textChunks.slice(i, i + EMBED_BATCH_SIZE)
- const embeddings = await embedFn(batch)
- if (embeddings.length !== batch.length) {
- throw new Error(`Embedding count mismatch: expected ${batch.length}, got ${embeddings.length}`)
- }
- for (let j = 0; j < batch.length; j++) {
- allChunks.push({
- content: batch[j],
- embedding: embeddings[j],
- chunkIndex: i + j,
- metadata: { chunkIndex: i + j, totalChunks: textChunks.length },
- })
- }
+ embedFnOf(params: { model: EmbeddingModel, providerOptions: SharedV3ProviderOptions }): EmbedFn {
+ const { model, providerOptions } = params
+ return async (texts) => {
+ const { embeddings } = await embedMany({ model, values: texts, providerOptions })
+ return embeddings.map((embedding) => aiUtils.toStorageEmbedding(embedding))
}
+ },
- await this.storeChunks({ projectId, knowledgeBaseFileId, chunks: allChunks })
+ async embedMissingChunks(params: EmbedMissingChunksParams): Promise<number> {
+ const { projectId, knowledgeBaseFileId, resolveEmbedFn } = params
+ const hasMissing = await kbChunkRepo().existsBy({ projectId, knowledgeBaseFileId, embedding: IsNull() })
+ if (!hasMissing) {
+ return 0
+ }
+ return distributedLock(log).runExclusive({
+ key: `knowledge_base_embed_${knowledgeBaseFileId}`,
+ timeoutInSeconds: 60,
+ fn: async () => {
+ const missing = await kbChunkRepo().find({
+ where: { projectId, knowledgeBaseFileId, embedding: IsNull() },
+ select: ['id', 'content'],
+ order: { chunkIndex: 'ASC' },
+ })
+ if (missing.length === 0) {
+ return 0
+ }
+ const embeddings = await embedAll({ texts: missing.map((chunk) => chunk.content), embedFn: await resolveEmbedFn() })
+ await transaction(async (entityManager) => {
+ for (let start = 0; start < missing.length; start += INSERT_BATCH_SIZE) {
+ const batch = missing.slice(start, start + INSERT_BATCH_SIZE)
+ await entityManager.query(
+ `UPDATE knowledge_base_chunk AS kbc
+ SET embedding = missing.embedding::vector
+ FROM unnest($1::varchar[], $2::text[], $3::text[]) AS missing(id, content, embedding)
+ WHERE kbc.id = missing.id AND kbc.content = missing.content AND kbc.embedding IS NULL
+ AND kbc."projectId" = $4 AND kbc."knowledgeBaseFileId" = $5`,
+ [batch.map((chunk) => chunk.id), batch.map((chunk) => chunk.content), embeddings.slice(start, start + INSERT_BATCH_SIZE).map(toVector), projectId, knowledgeBaseFileId],
+ )
+ }
+ })
+ return missing.length
+ },
+ })
},
async search(params: SearchParams): Promise<SearchResult[]> {
const { projectId, knowledgeBaseFileIds, queryEmbedding, limit, similarityThreshold } = params
- const embeddingStr = `[${queryEmbedding.join(',')}]`
+ const embeddingStr = toVector(queryEmbedding)
const results = await databaseConnection().query(
`SELECT kbc.id, kbc.content, kbc.metadata, kbc."chunkIndex",
@@ -186,11 +292,12 @@ export const knowledgeBaseService = (log: FastifyBaseLogger) => ({
},
async isSearchable(params: { projectId: string, knowledgeBaseFileId: string }): Promise<boolean> {
- return kbChunkRepo().existsBy({
- projectId: params.projectId,
- knowledgeBaseFileId: params.knowledgeBaseFileId,
- embedding: Not(IsNull()),
- })
+ const { projectId, knowledgeBaseFileId } = params
+ const [hasChunks, hasUnindexedChunks] = await Promise.all([
+ kbChunkRepo().existsBy({ projectId, knowledgeBaseFileId }),
+ kbChunkRepo().existsBy({ projectId, knowledgeBaseFileId, embedding: IsNull() }),
+ ])
+ return hasChunks && !hasUnindexedChunks
},
async extractChunks(params: { projectId: string, knowledgeBaseFileId: string }): Promise<string[]> {
@@ -213,13 +320,7 @@ export const knowledgeBaseService = (log: FastifyBaseLogger) => ({
fileId: kbFile.fileId,
})
- const fileName = fileData.fileName || kbFile.displayName
- if (fileName.toLowerCase().endsWith('.csv')) {
- return chunkCsvText(fileData.data.toString('utf-8'))
- }
-
- const text = await extractTextFromFile(fileData.data, fileName)
- return chunkText(text)
+ return chunksOf({ data: fileData.data, fileName: fileData.fileName || kbFile.displayName })
},
async storeChunks(params: StoreChunksParams): Promise<void> {
@@ -248,7 +349,7 @@ export const knowledgeBaseService = (log: FastifyBaseLogger) => ({
for (const [position, chunk] of chunks.entries()) {
const values = {
...spreadIfDefined('content', chunk.content),
- ...spreadIfDefined('embedding', chunk.embedding ? `[${chunk.embedding.join(',')}]` : undefined),
+ ...spreadIfDefined('embedding', chunk.embedding ? toVector(chunk.embedding) : undefined),
...spreadIfDefined('metadata', chunk.metadata),
}
if (isNil(chunk.id)) {
@@ -338,10 +439,23 @@ export const knowledgeBaseService = (log: FastifyBaseLogger) => ({
},
})
-type IngestFileParams = {
+export const KNOWLEDGE_BASE_NEEDS_AI_PROVIDER = 'KNOWLEDGE_BASE_NEEDS_AI_PROVIDER'
+export const KNOWLEDGE_BASE_FILE_HAS_NO_TEXT = 'KNOWLEDGE_BASE_FILE_HAS_NO_TEXT'
+
+type UploadFileParams = {
+ projectId: string
+ data: Buffer
+ fileName: string
+ displayName: string
+ embedFn: EmbedFn
+}
+
+type EmbedFn = (texts: string[]) => Promise<number[][]>
+
+type EmbedMissingChunksParams = {
projectId: string
knowledgeBaseFileId: string
- embedFn: (texts: string[]) => Promise<number[][]>
+ resolveEmbedFn: () => Promise<EmbedFn>
}
type SearchParams = {
diff --git a/packages/server/api/test/integration/ce/knowledge-base/knowledge-base-billing.test.ts b/packages/server/api/test/integration/ce/knowledge-base/knowledge-base-billing.test.ts
new file mode 100644
index 00000000000..cb5bf5cdf02
--- /dev/null
+++ b/packages/server/api/test/integration/ce/knowledge-base/knowledge-base-billing.test.ts
@@ -0,0 +1,85 @@
+import { ActivepiecesAiCostEvent, AiChargeBasis, AIProviderName } from '@activepieces/core-utils'
+import { activepiecesAiCost } from '@activepieces/server-utils'
+import { FastifyInstance } from 'fastify'
+import FormData from 'form-data'
+import { StatusCodes } from 'http-status-codes'
+import { mockAndSaveAIProvider } from '../../../helpers/mocks'
+import { createTestContext, TestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+beforeEach(() => {
+ vi.stubEnv('AP_OPENROUTER_PROVISION_KEY', 'test-provision-key')
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllEnvs()
+})
+
+function embeddingResponse(): Response {
+ return new Response(JSON.stringify({
+ id: 'gen-embed-1',
+ object: 'list',
+ data: [{ object: 'embedding', index: 0, embedding: Array.from({ length: 1536 }, () => 0.1) }],
+ model: 'openai/text-embedding-3-small',
+ usage: { prompt_tokens: 8, total_tokens: 8, cost: 0.00042 },
+ }), { status: 200, headers: { 'content-type': 'application/json' } })
+}
+
+function upload({ ctx }: { ctx: TestContext }) {
+ const form = new FormData()
+ form.append('displayName', 'Handbook')
+ form.append('file', Buffer.from('The office closes at six.'), { filename: 'doc.txt', contentType: 'text/plain' })
+ return app.inject({
+ method: 'POST',
+ url: `/api/v1/knowledge-base/files/upload?projectId=${ctx.project.id}`,
+ headers: { ...form.getHeaders(), authorization: `Bearer ${ctx.token}` },
+ payload: form.getBuffer(),
+ })
+}
+
+describe('embedding an upload on the managed provider', () => {
+ it('charges the owning platform and project what the provider reports', async () => {
+ const events: ActivepiecesAiCostEvent[] = []
+ activepiecesAiCost.setReporter((event) => {
+ events.push(event)
+ })
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async () => embeddingResponse())
+ const ctx = await createTestContext(app)
+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ACTIVEPIECES, enabledForChat: true })
+
+ const response = await upload({ ctx })
+
+ expect(response.statusCode).toBe(StatusCodes.CREATED)
+ expect(events).toHaveLength(1)
+ expect(events[0].billing.platformId).toBe(ctx.platform.id)
+ expect(events[0].billing.projectId).toBe(ctx.project.id)
+ expect(events[0].call.charge).toBe(AiChargeBasis.PROVIDER_REPORTED_COST)
+ expect(events[0].call).toMatchObject({ costUsd: 0.00042 })
+ })
+
+ it('does not charge an own-key provider', async () => {
+ const events: ActivepiecesAiCostEvent[] = []
+ activepiecesAiCost.setReporter((event) => {
+ events.push(event)
+ })
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async () => embeddingResponse())
+ const ctx = await createTestContext(app)
+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENROUTER, enabledForChat: true })
+
+ const response = await upload({ ctx })
+
+ expect(response.statusCode).toBe(StatusCodes.CREATED)
+ expect(events).toHaveLength(0)
+ })
+})
diff --git a/packages/server/api/test/integration/ce/knowledge-base/knowledge-base-upload.test.ts b/packages/server/api/test/integration/ce/knowledge-base/knowledge-base-upload.test.ts
index 7b4ce3e9663..0f7bdac548f 100644
--- a/packages/server/api/test/integration/ce/knowledge-base/knowledge-base-upload.test.ts
+++ b/packages/server/api/test/integration/ce/knowledge-base/knowledge-base-upload.test.ts
@@ -1,11 +1,48 @@
+import { AIProviderName, apId } from '@activepieces/core-utils'
+import { FileCompression, FileType, PrincipalType } from '@activepieces/shared'
import { FastifyInstance } from 'fastify'
import FormData from 'form-data'
import { StatusCodes } from 'http-status-codes'
-import { createTestContext } from '../../../helpers/test-context'
+import { KNOWLEDGE_BASE_FILE_HAS_NO_TEXT, KNOWLEDGE_BASE_NEEDS_AI_PROVIDER, knowledgeBaseService } from '../../../../src/app/knowledge-base/knowledge-base.service'
+import { generateMockToken } from '../../../helpers/auth'
+import { db } from '../../../helpers/db'
+import { createMockFile, mockAndSaveAIProvider } from '../../../helpers/mocks'
+import { createTestContext, TestContext } from '../../../helpers/test-context'
import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+vi.mock('ai', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ai')>()
+ return {
+ ...actual,
+ embedMany: async ({ values }: { values: string[] }) => ({
+ embeddings: values.map((value) => vectorFor(value)),
+ }),
+ }
+})
+
let app: FastifyInstance
+function vectorFor(text: string): number[] {
+ const topic = text.includes('invoice') ? 1 : 0
+ return Array.from({ length: 1536 }, (_, i) => (i === topic ? 1 : 0.01))
+}
+
+function search({ ctx, knowledgeBaseFileIds, query }: { ctx: TestContext, knowledgeBaseFileIds: string[], query: string }) {
+ return generateMockToken({ type: PrincipalType.ENGINE, id: apId(), projectId: ctx.project.id, platform: { id: ctx.platform.id } }).then((engineToken) => app.inject({
+ method: 'POST',
+ url: '/api/v1/knowledge-base/files/search',
+ headers: { authorization: `Bearer ${engineToken}` },
+ body: { knowledgeBaseFileIds, queryEmbedding: vectorFor(query).slice(0, 768), limit: 1 },
+ }))
+}
+
+function textFile({ name, content }: { name: string, content: string }): FormData {
+ const form = new FormData()
+ form.append('displayName', name)
+ form.append('file', Buffer.from(content), { filename: name, contentType: name.endsWith('.csv') ? 'text/csv' : 'text/plain' })
+ return form
+}
+
beforeAll(async () => {
app = await setupTestEnvironment()
})
@@ -14,11 +51,29 @@ afterAll(async () => {
await teardownTestEnvironment()
})
+async function contextWithProvider(): Promise<TestContext> {
+ const ctx = await createTestContext(app)
+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, enabledForChat: true })
+ return ctx
+}
+
+function upload({ ctx, form }: { ctx: TestContext, form: FormData }) {
+ return app.inject({
+ method: 'POST',
+ url: `/api/v1/knowledge-base/files/upload?projectId=${ctx.project.id}`,
+ headers: {
+ ...form.getHeaders(),
+ authorization: `Bearer ${ctx.token}`,
+ },
+ payload: form.getBuffer(),
+ })
+}
+
describe('POST /v1/knowledge-base/files/upload', () => {
// The web UI appends the file before displayName, so field order must not matter.
// Uses a multi-chunk file so busboy cannot have parsed the trailing field up front.
it('should accept displayName appended after the file', async () => {
- const ctx = await createTestContext(app)
+ const ctx = await contextWithProvider()
const form = new FormData()
form.append('file', Buffer.alloc(512 * 1024, 'a'), {
@@ -27,22 +82,14 @@ describe('POST /v1/knowledge-base/files/upload', () => {
})
form.append('displayName', 'My Document')
- const response = await app.inject({
- method: 'POST',
- url: `/api/v1/knowledge-base/files/upload?projectId=${ctx.project.id}`,
- headers: {
- ...form.getHeaders(),
- authorization: `Bearer ${ctx.token}`,
- },
- payload: form.getBuffer(),
- })
+ const response = await upload({ ctx, form })
expect(response.statusCode).toBe(StatusCodes.CREATED)
expect(response.json().displayName).toBe('My Document')
})
it('should accept displayName appended before the file', async () => {
- const ctx = await createTestContext(app)
+ const ctx = await contextWithProvider()
const form = new FormData()
form.append('displayName', 'My Document')
@@ -51,17 +98,103 @@ describe('POST /v1/knowledge-base/files/upload', () => {
contentType: 'text/plain',
})
- const response = await app.inject({
- method: 'POST',
- url: `/api/v1/knowledge-base/files/upload?projectId=${ctx.project.id}`,
- headers: {
- ...form.getHeaders(),
- authorization: `Bearer ${ctx.token}`,
- },
- payload: form.getBuffer(),
- })
+ const response = await upload({ ctx, form })
expect(response.statusCode).toBe(StatusCodes.CREATED)
expect(response.json().displayName).toBe('My Document')
})
+
+ it('finds the uploaded text when searched, not just any chunk', async () => {
+ const ctx = await contextWithProvider()
+ const handbook = await upload({ ctx, form: textFile({ name: 'handbook.txt', content: 'The office closes at six.' }) })
+ const billing = await upload({ ctx, form: textFile({ name: 'billing.txt', content: 'Every invoice is due in thirty days.' }) })
+
+ const response = await search({ ctx, knowledgeBaseFileIds: [handbook.json().id, billing.json().id], query: 'when is an invoice due' })
+
+ expect(response.json().map((row: { content: string }) => row.content)).toEqual(['Every invoice is due in thirty days.'])
+ })
+
+ it('embeds every chunk an old upload left unembedded, however long the file', async () => {
+ const ctx = await contextWithProvider()
+ const service = knowledgeBaseService(app.log)
+ const storedFile = createMockFile({ projectId: ctx.project.id, platformId: ctx.platform.id, data: Buffer.from('x'), type: FileType.KNOWLEDGE_BASE, compression: FileCompression.NONE, fileName: 'old.txt' })
+ await db.save('file', storedFile)
+ const file = await service.createFile({ projectId: ctx.project.id, fileId: storedFile.id, displayName: 'Old upload' })
+ const chunkCount = 250
+ await service.storeChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, chunks: Array.from({ length: chunkCount }, (_, chunkIndex) => ({ content: `Part ${chunkIndex}`, chunkIndex })) })
+
+ const embedded = await service.embedMissingChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, resolveEmbedFn: async () => async (texts) => texts.map(() => vectorFor('').slice(0, 768)) })
+
+ expect(embedded).toBe(chunkCount)
+ expect(await service.listChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, embedded: false })).toHaveLength(0)
+ })
+
+ it('does not count a file as searchable while any of its chunks is unindexed', async () => {
+ const ctx = await contextWithProvider()
+ const service = knowledgeBaseService(app.log)
+ const storedFile = createMockFile({ projectId: ctx.project.id, platformId: ctx.platform.id, data: Buffer.from('x'), type: FileType.KNOWLEDGE_BASE, compression: FileCompression.NONE, fileName: 'old.txt' })
+ await db.save('file', storedFile)
+ const file = await service.createFile({ projectId: ctx.project.id, fileId: storedFile.id, displayName: 'Half indexed' })
+ await service.storeChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, chunks: [
+ { content: 'The office closes at six.', chunkIndex: 0, embedding: vectorFor('office').slice(0, 768) },
+ { content: 'Every invoice is due in thirty days.', chunkIndex: 1 },
+ ] })
+
+ expect(await service.isSearchable({ projectId: ctx.project.id, knowledgeBaseFileId: file.id })).toBe(false)
+ })
+
+ it('does not save an embedding onto a chunk whose text changed while it was being embedded', async () => {
+ const ctx = await contextWithProvider()
+ const service = knowledgeBaseService(app.log)
+ const storedFile = createMockFile({ projectId: ctx.project.id, platformId: ctx.platform.id, data: Buffer.from('x'), type: FileType.KNOWLEDGE_BASE, compression: FileCompression.NONE, fileName: 'old.txt' })
+ await db.save('file', storedFile)
+ const file = await service.createFile({ projectId: ctx.project.id, fileId: storedFile.id, displayName: 'Edited meanwhile' })
+ await service.storeChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, chunks: [{ content: 'The office closes at six.', chunkIndex: 0 }] })
+ const [chunk] = await service.listChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id })
+
+ await service.embedMissingChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, resolveEmbedFn: async () => async (texts) => {
+ await service.storeChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, chunks: [{ id: chunk.id, content: 'The office now closes at five.' }] })
+ return texts.map(() => vectorFor('').slice(0, 768))
+ } })
+
+ expect(await service.listChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, embedded: false })).toHaveLength(1)
+ })
+
+ it('does not index an old upload from the read-only search route', async () => {
+ const ctx = await contextWithProvider()
+ const service = knowledgeBaseService(app.log)
+ const storedFile = createMockFile({ projectId: ctx.project.id, platformId: ctx.platform.id, data: Buffer.from('x'), type: FileType.KNOWLEDGE_BASE, compression: FileCompression.NONE, fileName: 'old.txt' })
+ await db.save('file', storedFile)
+ const file = await service.createFile({ projectId: ctx.project.id, fileId: storedFile.id, displayName: 'Old upload' })
+ await service.storeChunks({ projectId: ctx.project.id, knowledgeBaseFileId: file.id, chunks: [{ content: 'The office closes at six.', chunkIndex: 0 }] })
+
+ const response = await search({ ctx, knowledgeBaseFileIds: [file.id], query: 'office' })
+
+ expect(response.json()).toHaveLength(0)
+ expect(await service.isSearchable({ projectId: ctx.project.id, knowledgeBaseFileId: file.id })).toBe(false)
+ })
+
+ it.each([
+ { name: 'blank.txt', content: ' \n ' },
+ { name: 'headers.csv', content: 'name,age\n' },
+ ])('refuses $name, which has no text to search, instead of listing it as uploaded', async ({ name, content }) => {
+ const ctx = await contextWithProvider()
+
+ const response = await upload({ ctx, form: textFile({ name, content }) })
+
+ expect(response.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response.json().params.message).toBe(KNOWLEDGE_BASE_FILE_HAS_NO_TEXT)
+ expect(await db.findBy('knowledge_base_file', { projectId: ctx.project.id })).toHaveLength(0)
+ expect(await db.findBy('file', { projectId: ctx.project.id })).toHaveLength(0)
+ })
+
+ it('refuses the upload when no AI provider can index it, instead of storing an unsearchable file', async () => {
+ const ctx = await createTestContext(app)
+
+ const response = await upload({ ctx, form: textFile({ name: 'doc.txt', content: 'The office closes at six.' }) })
+
+ expect(response.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response.json().params.message).toBe(KNOWLEDGE_BASE_NEEDS_AI_PROVIDER)
+ expect(await db.findBy('knowledge_base_file', { projectId: ctx.project.id })).toHaveLength(0)
+ })
})
diff --git a/packages/server/api/test/integration/ee/agent/agent-knowledge-honesty.test.ts b/packages/server/api/test/integration/ee/agent/agent-knowledge-honesty.test.ts
index 53140fc6153..25aa258607d 100644
--- a/packages/server/api/test/integration/ee/agent/agent-knowledge-honesty.test.ts
+++ b/packages/server/api/test/integration/ee/agent/agent-knowledge-honesty.test.ts
@@ -68,18 +68,18 @@ describe('an agent asked about a file it cannot search says so', () => {
const { result } = await search(target)
- expect(String(result)).toContain('never been indexed')
+ expect(String(result)).toContain('could not be indexed')
expect(String(result)).toContain('Employee Handbook')
expect(String(result)).not.toContain('No relevant information found')
})
- it('does not send the person off to re-upload, which would not index it either', async () => {
+ it('points the person to uploading again, which says why the file cannot be indexed', async () => {
const ctx = await createTestContext(app, { plan: { agentsEnabled: true, chatEnabled: true } })
const target = await conversationWithFile(ctx)
const { result } = await search(target)
- expect(String(result)).toContain('will not index it either')
+ expect(String(result)).toContain('uploading the file again will say why')
})
it('does not read a file belonging to another project', async () => {
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index 6805172cdaf..61018db1bec 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -3155,5 +3155,7 @@
"Bring your own AI provider keys and choose the models that power your automations": "Bring your own AI provider keys and choose the models that power your automations",
"Connect OpenAI, Anthropic, Google and more": "Connect OpenAI, Anthropic, Google and more",
"Pick the default model for each AI capability": "Pick the default model for each AI capability",
- "Pay your provider directly, with no model markup": "Pay your provider directly, with no model markup"
+ "Pay your provider directly, with no model markup": "Pay your provider directly, with no model markup",
+ "Add an AI provider before uploading. Files are indexed when uploaded so agents can search them.": "Add an AI provider before uploading. Files are indexed when uploaded so agents can search them.",
+ "This file has no text that can be searched.": "This file has no text that can be searched."
}
diff --git a/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/index.tsx b/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/index.tsx
index 469b248a0d5..aa2197675f7 100644
--- a/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/index.tsx
+++ b/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/index.tsx
@@ -120,9 +120,6 @@ function KnowledgeBaseDialogContent({
handleSourceSelect(kbFile.id, kbFile.displayName);
toast(t('File uploaded successfully'));
},
- onError: () => {
- toast.error(t('Failed to upload file'));
- },
});
if (fileInputRef.current) {
diff --git a/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks.ts b/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks.ts
index 678ab3329e9..66b2db1fb4a 100644
--- a/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks.ts
+++ b/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks.ts
@@ -1,7 +1,10 @@
import { KnowledgeBaseFile } from '@activepieces/shared';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { t } from 'i18next';
+import { toast } from 'sonner';
import { authenticationSession } from '@/lib/authentication-session';
+import { validationUtils } from '@/lib/validation-utils';
import { knowledgeBaseApi } from './knowledge-base-api';
@@ -18,6 +21,9 @@ export const useUploadKnowledgeBaseFile = () => {
const projectId = authenticationSession.getProjectId();
return useMutation<KnowledgeBaseFile, Error, FormData>({
mutationFn: (formData: FormData) => knowledgeBaseApi.upload(formData),
+ onError: (error) => {
+ toast.error(uploadErrorMessage(error));
+ },
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['knowledge-base-files', projectId],
@@ -38,3 +44,17 @@ export const useDeleteKnowledgeBaseFile = () => {
},
});
};
+
+function uploadErrorMessage(error: unknown): string {
+ if (validationUtils.isValidationError(error)) {
+ switch (error.response?.data?.params?.message) {
+ case 'KNOWLEDGE_BASE_NEEDS_AI_PROVIDER':
+ return t(
+ 'Add an AI provider before uploading. Files are indexed when uploaded so agents can search them.',
+ );
+ case 'KNOWLEDGE_BASE_FILE_HAS_NO_TEXT':
+ return t('This file has no text that can be searched.');
+ }
+ }
+ return t('Failed to upload file');
+}