The minimalistic document archiving platform.
refactor(document-enrichment): centralize tagging (#1590)
Corentin Thomasset648c223b8075
diff --git a/.changeset/wide-tools-visit.md b/.changeset/wide-tools-visit.mdnew file mode 100644index 00000000..79a0bb9a--- /dev/null+++ b/.changeset/wide-tools-visit.md@@ -0,0 +1,5 @@+---+'@papra/app': patch+---++Refactor AI auto-tagging to use a capability-based document enrichment pipeline, preparing for additional enrichment features.diff --git a/apps/papra-server/src/modules/ai-credits/ai-credits.types.ts b/apps/papra-server/src/modules/ai-credits/ai-credits.types.tsindex be045eee..a3b11b99 100644--- a/apps/papra-server/src/modules/ai-credits/ai-credits.types.ts+++ b/apps/papra-server/src/modules/ai-credits/ai-credits.types.ts@@ -15,4 +15,4 @@ export type AiCreditsUsageDetails =creditsRate: ContentExtractionCreditRate;};-export type AiCreditsUsageSource = 'auto-tagging' | 'content-extraction';+export type AiCreditsUsageSource = 'auto-tagging' | 'content-extraction' | 'document-enrichment';diff --git a/apps/papra-server/src/modules/auto-tagging/auto-tagging.models.test.ts b/apps/papra-server/src/modules/auto-tagging/auto-tagging.models.test.tsindex 9d0ec974..87d5f3cc 100644--- a/apps/papra-server/src/modules/auto-tagging/auto-tagging.models.test.ts+++ b/apps/papra-server/src/modules/auto-tagging/auto-tagging.models.test.ts@@ -1,106 +1,7 @@import { describe, expect, test } from 'vitest';-import {- buildAutoTaggingSystemPrompt,- buildAutoTaggingUserPrompt,- getTagsActions,-} from './auto-tagging.models';+import { getTagsActions } from './auto-tagging.models';describe('auto-tagging.models', () => {- describe('buildAutoTaggingSystemPrompt', () => {- describe('prompt regression tests', () => {- const existingTags = [- {- name: 'Finance',- description:- 'Documents related to financial matters, including budgets, reports, and transactions.',- },- {- name: 'Household',- description: 'Documents related to household matters, including bills and maintenance.',- },- ];-- test('when there are existing tags and new tags can be created', () => {- expect(- buildAutoTaggingSystemPrompt({- canCreateNewTags: true,- existingTags,- maxTags: 5,- }),- ).toMatchInlineSnapshot(`- "You are an assistant that categorizes documents by selecting the most relevant tags based on their content.-- Available tags:- - Finance: Documents related to financial matters, including budgets, reports, and transactions.- - Household: Documents related to household matters, including bills and maintenance.-- Instructions:- - Select at most 5 tags, only those genuinely relevant to the document. Returning fewer is better than forcing irrelevant tags.- - Prefer the existing tags listed above whenever one fits.- - If none of the existing tags fit well, you may propose new, concise tag names. You may provide an optional description for each new tag."- `);- });-- test('when there are existing tags and new tags cannot be created', () => {- expect(- buildAutoTaggingSystemPrompt({- canCreateNewTags: false,- existingTags,- maxTags: 5,- }),- ).toMatchInlineSnapshot(`- "You are an assistant that categorizes documents by selecting the most relevant tags based on their content.-- Available tags:- - Finance: Documents related to financial matters, including budgets, reports, and transactions.- - Household: Documents related to household matters, including bills and maintenance.-- Instructions:- - Select at most 5 tags, only those genuinely relevant to the document. Returning fewer is better than forcing irrelevant tags.- - Prefer the existing tags listed above whenever one fits.- - Only choose from the existing tags listed above. Do not invent new tags."- `);- });-- test('when there are no existing tags and new tags can be created', () => {- expect(- buildAutoTaggingSystemPrompt({- canCreateNewTags: true,- existingTags: [],- maxTags: 3,- }),- ).toMatchInlineSnapshot(`- "You are an assistant that categorizes documents by creating the most relevant tags based on their content.-- Instructions:- - Create at most 3 tags, only those genuinely relevant to the document. Returning fewer is better than forcing irrelevant tags.- - If you cannot think of any relevant tags, return an empty list.- - The tags should be concise and useful for categorizing documents.- - You may provide an optional description for each tag."- `);- });- });- });-- describe('buildAutoTaggingUserPrompt', () => {- test('the document name and content are simply inlined', () => {- expect(- buildAutoTaggingUserPrompt({- document: {- name: 'My Document',- content:- 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.\nSed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',- },- }),- ).toMatchInlineSnapshot(`- "Document name: My Document- Document content:- Lorem ipsum dolor sit amet, consectetur adipiscing elit.- Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."- `);- });- });-describe('getTagsActions', () => {describe('the structured data returned by the AI depends on the context (can create new tags, is there existing tags, etc.)', () => {const existingTags = [diff --git a/apps/papra-server/src/modules/auto-tagging/auto-tagging.models.ts b/apps/papra-server/src/modules/auto-tagging/auto-tagging.models.tsindex a7748fd2..fc6e8843 100644--- a/apps/papra-server/src/modules/auto-tagging/auto-tagging.models.ts+++ b/apps/papra-server/src/modules/auto-tagging/auto-tagging.models.ts@@ -1,88 +1,10 @@-import * as v from 'valibot';import { uniq } from '../shared/utils';-function buildTagLine({ name, description }: { name: string; description?: string | null }) {- return description ? `- ${name}: ${description}` : `- ${name}`;-}--export function buildAutoTaggingSystemPrompt({- existingTags,- canCreateNewTags,- maxTags,-}: {- existingTags: { name: string; description?: string | null }[];- canCreateNewTags: boolean;- maxTags: number;-}) {- if (existingTags.length > 0) {- return [- 'You are an assistant that categorizes documents by selecting the most relevant tags based on their content.',- '',-- 'Available tags:',- ...existingTags.map(buildTagLine),- '',- 'Instructions:',- `- Select at most ${maxTags} tag${maxTags === 1 ? '' : 's'}, only those genuinely relevant to the document. Returning fewer is better than forcing irrelevant tags.`,- '- Prefer the existing tags listed above whenever one fits.',- canCreateNewTags- ? '- If none of the existing tags fit well, you may propose new, concise tag names. You may provide an optional description for each new tag.'- : '- Only choose from the existing tags listed above. Do not invent new tags.',- ].join('\n');- }-- // No existing tags, and we are sure that new tags can be created, so we make the prompt all about creating new tags.- return [- 'You are an assistant that categorizes documents by creating the most relevant tags based on their content.',- '',- 'Instructions:',- `- Create at most ${maxTags} tag${maxTags === 1 ? '' : 's'}, only those genuinely relevant to the document. Returning fewer is better than forcing irrelevant tags.`,- '- If you cannot think of any relevant tags, return an empty list.',- '- The tags should be concise and useful for categorizing documents.',- '- You may provide an optional description for each tag.',- ].join('\n');-}--export function buildAutoTaggingUserPrompt({- document,-}: {- document: { content: string; name: string };-}) {- return [`Document name: ${document.name}`, 'Document content:', document.content].join('\n');-}-export type AutoTaggingResponse = {existingTags?: string[];newTags?: { name: string; description?: string }[];};-export function buildAutoTaggingSchema({- existingTags,- canCreateNewTags,-}: {- existingTags: { name: string; description?: string | null }[];- canCreateNewTags: boolean;-}): v.GenericSchema<AutoTaggingResponse> {- const hasExistingTags = existingTags.length > 0;-- if (canCreateNewTags && hasExistingTags) {- return v.object({- existingTags: v.array(v.picklist(existingTags.map((tag) => tag.name))),- newTags: v.array(v.object({ name: v.string(), description: v.optional(v.string()) })),- });- }-- if (canCreateNewTags && !hasExistingTags) {- return v.object({- newTags: v.array(v.object({ name: v.string(), description: v.optional(v.string()) })),- });- }-- return v.object({- existingTags: v.array(v.picklist(existingTags.map((tag) => tag.name))),- });-}-export type AutoTaggingActions = {tagIdsToAdd: string[];tagsToCreate: { name: string; description?: string }[];diff --git a/apps/papra-server/src/modules/auto-tagging/auto-tagging.usecases.test.ts b/apps/papra-server/src/modules/auto-tagging/auto-tagging.usecases.test.tsindex 78dd674b..20109b1d 100644--- a/apps/papra-server/src/modules/auto-tagging/auto-tagging.usecases.test.ts+++ b/apps/papra-server/src/modules/auto-tagging/auto-tagging.usecases.test.ts@@ -1,27 +1,12 @@-import { describe, expect, test, vi } from 'vitest';-import * as v from 'valibot';+import { describe, expect, test } from 'vitest';import { createInMemoryDatabase } from '../app/database/database.test-utils';import { createTestEventServices } from '../app/events/events.test-utils';-import type { AiServices } from '../ai/ai.services';import { overrideConfig } from '../config/config.test-utils';import { createTestLogger } from '../shared/logger/logger.test-utils';import { createTagsRepository } from '../tags/tags.repository';import { documentsTagsTable, tagsTable } from '../tags/tags.table';import { applyTagsToDocuments, createTag } from '../tags/tags.usecases';-import { buildApplyAutoTaggingActions, buildPromptForAutoTagging } from './auto-tagging.usecases';-import type { AutoTaggingResponse } from './auto-tagging.models';-import { buildAutoTaggingSystemPrompt, buildAutoTaggingUserPrompt } from './auto-tagging.models';--function createTestAiServices({ response }: { response: AutoTaggingResponse }) {- const generateStructuredData = vi- .fn<AiServices['generateStructuredData']>()- .mockResolvedValue(response);-- return {- aiServices: { generateStructuredData } as AiServices,- generateStructuredData,- };-}+import { buildApplyAutoTaggingActions } from './auto-tagging.usecases';async function createTestDeps(seedOptions: Parameters<typeof createInMemoryDatabase>[0],@@ -81,45 +66,6 @@ const seed = {};describe('auto-tagging usecases', () => {- describe('buildPromptForAutoTagging', () => {- test('analysis uses the existing prompts and accounting source and returns bounded tag actions without applying them', async () => {- const { aiServices, generateStructuredData } = createTestAiServices({- response: {- existingTags: ['Finance', 'Finance', 'Unknown'],- newTags: [{ name: 'Invoice', description: 'Invoices and receipts' }, { name: 'Other' }],- },- });- const promptForAutoTagging = buildPromptForAutoTagging({ aiServices });- const options = { existingTags: seed.tags, canCreateNewTags: true, maxTags: 2 };-- expect(- await promptForAutoTagging({- document: baseDocument,- modelId: 'openai://gpt-4',- ...options,- }),- ).toEqual({- tagIdsToAdd: ['tag_1'],- tagsToCreate: [{ name: 'Invoice', description: 'Invoices and receipts' }],- });- expect(generateStructuredData).toHaveBeenCalledTimes(1);- const [request] = generateStructuredData.mock.calls[0]!;- expect(request).toMatchObject({- organizationId: 'org_1',- modelId: 'openai://gpt-4',- source: 'auto-tagging',- systemPrompt: buildAutoTaggingSystemPrompt(options),- userPrompt: buildAutoTaggingUserPrompt({ document: baseDocument }),- });- expect(- v.safeParse(request.schema!, { existingTags: ['Finance'], newTags: [] }).success,- ).toEqual(true);- expect(- v.safeParse(request.schema!, { existingTags: ['Unknown'], newTags: [] }).success,- ).toEqual(false);- });- });-describe('buildApplyAutoTaggingActions', () => {test('existing and successfully created tags are applied despite a creation failure, preserving current tags and emitting the domain event', async () => {const deps = await createTestDeps(seed);diff --git a/apps/papra-server/src/modules/auto-tagging/auto-tagging.usecases.ts b/apps/papra-server/src/modules/auto-tagging/auto-tagging.usecases.tsindex e33e6992..8846c681 100644--- a/apps/papra-server/src/modules/auto-tagging/auto-tagging.usecases.ts+++ b/apps/papra-server/src/modules/auto-tagging/auto-tagging.usecases.ts@@ -1,4 +1,3 @@-import type { AiServices } from '../ai/ai.services';import type { Tag } from '../tags/tags.types';import type {applyTagsToDocuments as applyTagsToDocumentsUsecase,@@ -6,43 +5,6 @@ import type {} from '../tags/tags.usecases';import pLimit from 'p-limit';import type { AutoTaggingActions } from './auto-tagging.models';-import {- buildAutoTaggingSchema,- buildAutoTaggingSystemPrompt,- buildAutoTaggingUserPrompt,- getTagsActions,-} from './auto-tagging.models';--export function buildPromptForAutoTagging({ aiServices }: { aiServices: AiServices }) {- return async ({- document,- existingTags,- canCreateNewTags,- maxTags,- modelId,- }: {- document: { content: string; name: string; organizationId: string };- existingTags: { id: string; name: string; description?: string | null }[];- canCreateNewTags: boolean;- maxTags: number;- modelId: string;- }): Promise<AutoTaggingActions> => {- const autoTaggingResponse = await aiServices.generateStructuredData({- modelId,- organizationId: document.organizationId,- source: 'auto-tagging',- schema: buildAutoTaggingSchema({ existingTags, canCreateNewTags }),- systemPrompt: buildAutoTaggingSystemPrompt({ existingTags, canCreateNewTags, maxTags }),- userPrompt: buildAutoTaggingUserPrompt({ document }),- });-- return getTagsActions({- autoTaggingResponse,- existingTags,- maxTags,- });- };-}export function buildApplyAutoTaggingActions({createTag,diff --git a/apps/papra-server/src/modules/auto-tagging/int-tests/auto-tagging.int.test-suites.ts b/apps/papra-server/src/modules/auto-tagging/int-tests/auto-tagging.int.test-suites.tsindex 18851c2d..05165226 100644--- a/apps/papra-server/src/modules/auto-tagging/int-tests/auto-tagging.int.test-suites.ts+++ b/apps/papra-server/src/modules/auto-tagging/int-tests/auto-tagging.int.test-suites.ts@@ -1,7 +1,12 @@-import { expect, test } from 'vitest';+import { expect, test, vi } from 'vitest';import type { Config } from '../../config/config.types';import { createAiServices } from '../../ai/ai.services';-import { buildPromptForAutoTagging } from '../auto-tagging.usecases';+import type { buildApplyAutoTaggingActions } from '../auto-tagging.usecases';+import { buildEnrichDocument } from '../../document-enrichment/document-enrichment.usecases';+import { buildTagsEnrichmentCapability } from '../../document-enrichment/enrichment-capabilities/tags/tags.enrichment-capability';+import { createDocumentsRepository } from '../../documents/documents.repository';+import { createTagsRepository } from '../../tags/tags.repository';+import { createTestLogger } from '../../shared/logger/logger.test-utils';import type { Logger } from '@crowlog/logger';import { createAiCreditsRepository } from '../../ai-credits/ai-credits.repository';import { createInMemoryDatabase } from '../../app/database/database.test-utils';@@ -31,14 +36,36 @@ const existingTags = [export async function runAutoTaggingTestSuite({modelId,- config,+ config: providerConfig,timeout = 20_000,}: {modelId: string;config: Config;timeout?: number;}) {- const { db } = await createInMemoryDatabase();+ const config = {+ ...providerConfig,+ ai: { ...providerConfig.ai, isEnabled: true },+ };+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: document.organizationId, name: 'Test organization' }],+ documents: [+ {+ ...document,+ id: 'doc_1',+ originalName: document.name,+ originalStorageKey: 'doc_1',+ originalSha256Hash: 'doc_1',+ mimeType: 'application/pdf',+ },+ ],+ tags: existingTags.map((tag) => ({+ ...tag,+ organizationId: document.organizationId,+ normalizedName: tag.name,+ color: '#000000',+ })),+ });const aiServices = createAiServices({config,@@ -51,17 +78,30 @@ export async function runAutoTaggingTestSuite({planEntitlementDefinitionRegistry: createPlanEntitlementDefinitionRegistry({ config }),});- const promptForAutoTagging = buildPromptForAutoTagging({ aiServices });+ const applyAutoTaggingActions = vi+ .fn<ReturnType<typeof buildApplyAutoTaggingActions>>()+ .mockResolvedValue();+ const { logger } = createTestLogger();+ const enrichDocument = buildEnrichDocument({+ aiServices,+ documentsRepository: createDocumentsRepository({ db }),+ tagsRepository: createTagsRepository({ db }),+ capabilityDefinitions: [buildTagsEnrichmentCapability({ config, applyAutoTaggingActions })],+ resolveOrganizationSettings: async () => ({+ organizationSettings: {+ ai: {+ autoTagging: { isEnabled: true, canCreateNewTags: false, maxTags: 3, modelId },+ },+ },+ }),+ logger,+ });- test('auto-tagging should correctly identify tags for a document', { timeout }, async () => {- const { tagIdsToAdd, tagsToCreate } = await promptForAutoTagging({- existingTags,- modelId,- canCreateNewTags: false,- document,- maxTags: 3,- });+ test('document enrichment identifies relevant tags for an invoice', { timeout }, async () => {+ await enrichDocument({ documentId: 'doc_1', organizationId: document.organizationId });+ expect(applyAutoTaggingActions).toHaveBeenCalledTimes(1);+ const [{ tagIdsToAdd, tagsToCreate }] = applyAutoTaggingActions.mock.calls[0]!;expect(tagsToCreate).toEqual([]);expect(tagIdsToAdd.length).toBeLessThanOrEqual(3);expect(tagIdsToAdd).toContain('tag_1'); // the document is unambiguously an invoicediff --git a/apps/papra-server/src/modules/document-enrichment/document-enrichment.usecases.test.ts b/apps/papra-server/src/modules/document-enrichment/document-enrichment.usecases.test.tsindex acce28f0..11a95265 100644--- a/apps/papra-server/src/modules/document-enrichment/document-enrichment.usecases.test.ts+++ b/apps/papra-server/src/modules/document-enrichment/document-enrichment.usecases.test.ts@@ -1,12 +1,10 @@import { describe, expect, test, vi } from 'vitest';+import * as v from 'valibot';import type { AiServices } from '../ai/ai.services';import { createInMemoryDatabase } from '../app/database/database.test-utils';import { createTestEventServices } from '../app/events/events.test-utils';import type { AutoTaggingResponse } from '../auto-tagging/auto-tagging.models';-import {- buildApplyAutoTaggingActions,- buildPromptForAutoTagging,-} from '../auto-tagging/auto-tagging.usecases';+import { buildApplyAutoTaggingActions } from '../auto-tagging/auto-tagging.usecases';import { overrideConfig } from '../config/config.test-utils';import { createDocumentNotFoundError } from '../documents/documents.errors';import { createDocumentsRepository } from '../documents/documents.repository';@@ -16,6 +14,7 @@ import { createTagsRepository } from '../tags/tags.repository';import { documentsTagsTable, tagsTable } from '../tags/tags.table';import { applyTagsToDocuments, createTag } from '../tags/tags.usecases';import { buildEnrichDocument } from './document-enrichment.usecases';+import { buildTagsEnrichmentCapability } from './enrichment-capabilities/tags/tags.enrichment-capability';function createTestResolveOrganizationSettings(autoTagging: Partial<{ isEnabled: boolean; canCreateNewTags: boolean; maxTags: number }> = {},@@ -46,9 +45,15 @@ function createTestAiServices({ response }: { response: AutoTaggingResponse }) {};}-async function createTestDeps(seedOptions: Parameters<typeof createInMemoryDatabase>[0]) {+async function createTestDeps(+ seedOptions: Parameters<typeof createInMemoryDatabase>[0],+ { isAiEnabled = true, isAutoTaggingEnabled = true } = {},+) {const { db } = await createInMemoryDatabase(seedOptions);- const config = overrideConfig();+ const config = overrideConfig({+ ai: { isEnabled: isAiEnabled },+ autoTagging: { isEnabled: isAutoTaggingEnabled },+ });const tagsRepository = createTagsRepository({ db });const eventServices = createTestEventServices();const { logger } = createTestLogger();@@ -58,11 +63,17 @@ async function createTestDeps(seedOptions: Parameters<typeof createInMemoryDatabdocumentsRepository: createDocumentsRepository({ db }),tagsRepository,logger,- applyAutoTaggingActions: buildApplyAutoTaggingActions({- createTag: async (args) => createTag({ ...args, config, tagsRepository }),- applyTagsToDocuments: async (args) =>- applyTagsToDocuments({ ...args, tagsRepository, eventServices, logger }),- }),+ config,+ capabilityDefinitions: [+ buildTagsEnrichmentCapability({+ config,+ applyAutoTaggingActions: buildApplyAutoTaggingActions({+ createTag: async (args) => createTag({ ...args, config, tagsRepository }),+ applyTagsToDocuments: async (args) =>+ applyTagsToDocuments({ ...args, tagsRepository, eventServices, logger }),+ }),+ }),+ ],};}@@ -70,7 +81,7 @@ const baseDocument = {id: 'doc_1',organizationId: 'org_1',name: 'Doc 1',- originalName: 'Doc 1',+ originalName: 'original.pdf',originalStorageKey: 'doc_1',originalSha256Hash: 'doc_1',mimeType: 'text/plain',@@ -86,6 +97,7 @@ const seed = {{id: 'tag_1',name: 'Finance',+ description: 'Financial documents',normalizedName: 'finance',color: '#000000',organizationId: 'org_1',@@ -101,6 +113,53 @@ const seed = {};describe('document enrichment', () => {+ test('when AI is disabled on the instance, the document is not tagged and the AI is not called', async () => {+ const deps = await createTestDeps(seed, { isAiEnabled: false });+ const { aiServices, generateStructuredData } = createTestAiServices({+ response: { existingTags: ['Finance'] },+ });+ const enrichDocument = buildEnrichDocument({+ ...deps,+ aiServices,+ resolveOrganizationSettings: createTestResolveOrganizationSettings(),+ });++ await enrichDocument(documentIds);++ expect(generateStructuredData).not.toHaveBeenCalled();+ expect(await deps.db.select().from(documentsTagsTable)).toEqual([]);+ });++ test('when auto-tagging is disabled on the instance, the document is not tagged and the AI is not called', async () => {+ const deps = await createTestDeps(seed, { isAutoTaggingEnabled: false });+ const { aiServices, generateStructuredData } = createTestAiServices({+ response: { existingTags: ['Finance'] },+ });+ const enrichDocument = buildEnrichDocument({+ ...deps,+ aiServices,+ resolveOrganizationSettings: createTestResolveOrganizationSettings(),+ });++ await enrichDocument(documentIds);++ expect(generateStructuredData).not.toHaveBeenCalled();+ expect(await deps.db.select().from(documentsTagsTable)).toEqual([]);+ });++ test('a missing document fails before analysis', async () => {+ const deps = await createTestDeps({ organizations: seed.organizations, tags: seed.tags });+ const { aiServices, generateStructuredData } = createTestAiServices({ response: {} });+ const enrichDocument = buildEnrichDocument({+ ...deps,+ aiServices,+ resolveOrganizationSettings: createTestResolveOrganizationSettings(),+ });++ await expect(enrichDocument(documentIds)).rejects.toEqual(createDocumentNotFoundError());+ expect(generateStructuredData).not.toHaveBeenCalled();+ });+test('when auto-tagging is disabled in the organization settings, the document is not tagged and the AI is not called', async () => {const deps = await createTestDeps(seed);const { aiServices, generateStructuredData } = createTestAiServices({@@ -108,7 +167,7 @@ describe('document enrichment', () => {});const enrichDocument = buildEnrichDocument({...deps,- promptForAutoTagging: buildPromptForAutoTagging({ aiServices }),+ aiServices,resolveOrganizationSettings: createTestResolveOrganizationSettings({ isEnabled: false }),});@@ -128,7 +187,7 @@ describe('document enrichment', () => {});const enrichDocument = buildEnrichDocument({...deps,- promptForAutoTagging: buildPromptForAutoTagging({ aiServices }),+ aiServices,resolveOrganizationSettings: createTestResolveOrganizationSettings({isEnabled: true,canCreateNewTags: false,@@ -143,10 +202,12 @@ describe('document enrichment', () => {test('when the AI selects existing tags, they are applied to the document', async () => {const deps = await createTestDeps(seed);- const { aiServices } = createTestAiServices({ response: { existingTags: ['Finance'] } });+ const { aiServices, generateStructuredData } = createTestAiServices({+ response: { existingTags: ['Finance'] },+ });const enrichDocument = buildEnrichDocument({...deps,- promptForAutoTagging: buildPromptForAutoTagging({ aiServices }),+ aiServices,resolveOrganizationSettings: createTestResolveOrganizationSettings(),});@@ -155,6 +216,80 @@ describe('document enrichment', () => {expect(await deps.db.select().from(documentsTagsTable)).toEqual([{ documentId: 'doc_1', tagId: 'tag_1' },]);+ expect(generateStructuredData).toHaveBeenCalledTimes(1);+ const [request] = generateStructuredData.mock.calls[0]!;+ expect(request).toMatchObject({+ organizationId: 'org_1',+ modelId: 'gpt-4',+ source: 'document-enrichment',+ });+ const { tags } = await deps.tagsRepository.getOrganizationTags(documentIds);+ expect(JSON.parse(request.userPrompt)).toEqual({+ document: { name: baseDocument.originalName, content: baseDocument.content },+ existingTags: tags.map(({ name, description }) => ({ name, description })),+ });+ expect(request.systemPrompt).toMatchInlineSnapshot(`+ "You enrich documents for an archiving application.++ Given extracted document text, an original filename, return:++ DOCUMENT TAGS++ - Suggest tags that are relevant to the document content.+ - Select at most 5 tags.+ - You may only suggest existing tags.+ - If no relevant tags can be found, return an empty list."+ `);+ expect(v.parse(request.schema!, { existingTags: ['Finance'] })).toEqual({+ existingTags: ['Finance'],+ });+ expect(v.safeParse(request.schema!, { existingTags: ['Unknown'] }).success).toEqual(false);+ });++ test('existing and new tag suggestions respect the organization limit and prefer existing tags', async () => {+ const deps = await createTestDeps(seed);+ const { aiServices, generateStructuredData } = createTestAiServices({+ response: {+ existingTags: ['Finance', 'Finance', 'Unknown'],+ newTags: [{ name: 'Invoice', description: 'Invoices and receipts' }, { name: 'Other' }],+ },+ });+ const enrichDocument = buildEnrichDocument({+ ...deps,+ aiServices,+ resolveOrganizationSettings: createTestResolveOrganizationSettings({+ canCreateNewTags: true,+ maxTags: 2,+ }),+ });++ await enrichDocument(documentIds);++ const tags = await deps.db.select().from(tagsTable);+ expect(tags.map(({ name }) => name).sort()).toEqual(['Finance', 'Household', 'Invoice']);+ const invoiceTag = tags.find(({ name }) => name === 'Invoice')!;+ expect(invoiceTag.description).toEqual('Invoices and receipts');+ const documentTags = await deps.db.select().from(documentsTagsTable);+ expect(documentTags.map(({ tagId }) => tagId).sort()).toEqual(['tag_1', invoiceTag.id].sort());+ const [request] = generateStructuredData.mock.calls[0]!;+ expect(request.systemPrompt).toMatchInlineSnapshot(`+ "You enrich documents for an archiving application.++ Given extracted document text, an original filename, return:++ DOCUMENT TAGS++ - Suggest tags that are relevant to the document content.+ - Select at most 2 tags.+ - You may suggest new tags that do not exist yet.+ - If you suggest new tags, provide an optional description for each new tag.+ - Do not suggest new tags that are too similar to existing tags."+ `);+ const response = { existingTags: ['Finance'], newTags: [{ name: 'Invoice' }] };+ expect(v.parse(request.schema!, response)).toEqual(response);+ expect(+ v.safeParse(request.schema!, { existingTags: ['Unknown'], newTags: [] }).success,+ ).toEqual(false);});test('when the AI proposes new tags, they are created and applied to the document', async () => {@@ -162,12 +297,11 @@ describe('document enrichment', () => {organizations: seed.organizations,documents: seed.documents,});- const { aiServices } = createTestAiServices({- response: { newTags: [{ name: 'Invoice', description: 'Invoices and receipts' }] },- });+ const response = { newTags: [{ name: 'Invoice', description: 'Invoices and receipts' }] };+ const { aiServices, generateStructuredData } = createTestAiServices({ response });const enrichDocument = buildEnrichDocument({...deps,- promptForAutoTagging: buildPromptForAutoTagging({ aiServices }),+ aiServices,resolveOrganizationSettings: createTestResolveOrganizationSettings({canCreateNewTags: true,}),@@ -175,6 +309,9 @@ describe('document enrichment', () => {await enrichDocument(documentIds);+ const [request] = generateStructuredData.mock.calls[0]!;+ expect(v.parse(request.schema!, response)).toEqual(response);+ expect(JSON.parse(request.userPrompt)).toMatchObject({ existingTags: [] });const createdTags = await deps.db.select().from(tagsTable);expect(createdTags.length).toEqual(1);expect(createdTags[0]).toMatchObject({@@ -188,57 +325,6 @@ describe('document enrichment', () => {]);});- test('the organization model and tag settings are passed to analysis and its actions are passed to application', async () => {- const deps = await createTestDeps(seed);- const actions = { tagIdsToAdd: ['tag_1'], tagsToCreate: [{ name: 'Invoice' }] };- const promptForAutoTagging = vi- .fn<ReturnType<typeof buildPromptForAutoTagging>>()- .mockResolvedValue(actions);- const applyAutoTaggingActions = vi- .fn<ReturnType<typeof buildApplyAutoTaggingActions>>()- .mockResolvedValue();- const enrichDocument = buildEnrichDocument({- ...deps,- promptForAutoTagging,- applyAutoTaggingActions,- resolveOrganizationSettings: createTestResolveOrganizationSettings({- maxTags: 2,- canCreateNewTags: true,- }),- });-- await enrichDocument(documentIds);-- expect(promptForAutoTagging).toHaveBeenCalledTimes(1);- const [request] = promptForAutoTagging.mock.calls[0]!;- expect(request).toMatchObject({- document: baseDocument,- canCreateNewTags: true,- maxTags: 2,- modelId: 'gpt-4',- });- expect(request.existingTags.toSorted((a, b) => a.id.localeCompare(b.id))).toMatchObject(- seed.tags,- );- expect(applyAutoTaggingActions).toHaveBeenCalledExactlyOnceWith({- ...documentIds,- ...actions,- });- });-- test('a missing document fails before analysis', async () => {- const deps = await createTestDeps({ organizations: seed.organizations, tags: seed.tags });- const promptForAutoTagging = vi.fn<ReturnType<typeof buildPromptForAutoTagging>>();- const enrichDocument = buildEnrichDocument({- ...deps,- promptForAutoTagging,- resolveOrganizationSettings: createTestResolveOrganizationSettings(),- });-- await expect(enrichDocument(documentIds)).rejects.toEqual(createDocumentNotFoundError());- expect(promptForAutoTagging).not.toHaveBeenCalled();- });-test('an inference failure is propagated without applying tags', async () => {const deps = await createTestDeps(seed);const error = new Error('Inference failed');@@ -247,8 +333,10 @@ describe('document enrichment', () => {const applyAutoTaggingActions = vi.fn<ReturnType<typeof buildApplyAutoTaggingActions>>();const enrichDocument = buildEnrichDocument({...deps,- promptForAutoTagging: buildPromptForAutoTagging({ aiServices }),- applyAutoTaggingActions,+ aiServices,+ capabilityDefinitions: [+ buildTagsEnrichmentCapability({ config: deps.config, applyAutoTaggingActions }),+ ],resolveOrganizationSettings: createTestResolveOrganizationSettings(),});diff --git a/apps/papra-server/src/modules/document-enrichment/document-enrichment.usecases.ts b/apps/papra-server/src/modules/document-enrichment/document-enrichment.usecases.tsindex 13b52209..090c686a 100644--- a/apps/papra-server/src/modules/document-enrichment/document-enrichment.usecases.ts+++ b/apps/papra-server/src/modules/document-enrichment/document-enrichment.usecases.ts@@ -1,9 +1,5 @@import type { Logger } from '@crowlog/logger';import { ensureModelId } from '../ai/ai.models';-import type {- buildApplyAutoTaggingActions,- buildPromptForAutoTagging,-} from '../auto-tagging/auto-tagging.usecases';import { createDocumentNotFoundError } from '../documents/documents.errors';import type { DocumentsRepository } from '../documents/documents.repository';import type { ResolveOrganizationSettingsUsecase } from '../organizations/organization-settings/organization-settings.usecases';@@ -16,6 +12,10 @@ import {createDocumentEnrichmentContentRequiredError,createDocumentEnrichmentDisabledError,} from './document-enrichment.errors';+import type { GenericObjectSchema } from '../shared/schemas/objects.schemas';+import type { DocumentEnrichmentCapabilityDefinition } from './enrichment-capabilities/enrichment-capabilities-definition';+import type { AiServices } from '../ai/ai.services';+import * as v from 'valibot';export function buildScheduleDocumentEnrichment({config,@@ -67,19 +67,22 @@ export function buildScheduleDocumentEnrichment({};}-export function buildEnrichDocument({- promptForAutoTagging,- applyAutoTaggingActions,+export function buildEnrichDocument<ResponseSchema extends GenericObjectSchema>({+ capabilityDefinitions,documentsRepository,tagsRepository,resolveOrganizationSettings,+ aiServices,logger = createLogger({ namespace: 'documentEnrichment' }),}: {- promptForAutoTagging: ReturnType<typeof buildPromptForAutoTagging>;- applyAutoTaggingActions: ReturnType<typeof buildApplyAutoTaggingActions>;+ capabilityDefinitions: DocumentEnrichmentCapabilityDefinition<+ DocumentEnrichmentCapability,+ ResponseSchema+ >[];documentsRepository: Pick<DocumentsRepository, 'getDocumentById'>;tagsRepository: Pick<TagsRepository, 'getOrganizationTags'>;resolveOrganizationSettings: ResolveOrganizationSettingsUsecase;+ aiServices: AiServices;logger?: Logger;}) {return async ({@@ -91,8 +94,15 @@ export function buildEnrichDocument({organizationId: string;capabilities?: DocumentEnrichmentCapability[];}) => {- // Automatic and previously queued jobs without a selection retain auto-tagging.- if (!capabilities.includes('auto-tagging')) {+ const selectedCapabilities = capabilityDefinitions.filter((capability) =>+ capabilities.includes(capability.name),+ );++ if (selectedCapabilities.length === 0) {+ logger.info(+ { documentId, organizationId, capabilities },+ 'No valid enrichment capabilities selected. Skipping enrichment.',+ );return;}@@ -102,44 +112,118 @@ export function buildEnrichDocument({resolveOrganizationSettings({ organizationId }),]);- const orgHasNoExistingTags = existingTags.length === 0;- const {- canCreateNewTags,- maxTags,- isEnabled: isAutoTaggingEnabled,- } = organizationSettings.ai.autoTagging;-- if (orgHasNoExistingTags && !canCreateNewTags) {- logger.info(- { documentId, organizationId },- 'No tags available and cannot create new tags. Skipping auto-tagging.',- );- return;+ if (!document || document.isDeleted) {+ throw createDocumentNotFoundError();}- if (!isAutoTaggingEnabled) {+ const availableCapabilities = selectedCapabilities.filter((capability) =>+ capability.isAvailable({ organizationSettings, tags: existingTags }),+ );++ if (availableCapabilities.length === 0) {logger.info(- { documentId, organizationId },- 'Auto-tagging is disabled in organization settings. Skipping auto-tagging.',+ { documentId, organizationId, capabilities },+ 'No enrichment capabilities are enabled for this organization or instance. Skipping enrichment.',);return;}- if (!document || document.isDeleted) {- throw createDocumentNotFoundError();- }+ const promptContext = availableCapabilities.map((capability) => ({+ capability,+ systemPromptFragments: capability.buildSystemPromptFragments({+ organizationSettings,+ tags: existingTags,+ }),+ responseSchema: capability.getResponseSchema({+ organizationSettings,+ tags: existingTags,+ }),+ }));++ const systemPromptSpecifics = promptContext+ .map((context) => context.systemPromptFragments.fragment)+ .join('\n\n');- const startedAt = Date.now();- const actions = await promptForAutoTagging({- document,- existingTags,- canCreateNewTags,- maxTags,+ const systemPrompt = [+ 'You enrich documents for an archiving application.',+ 'Given extracted document text, an original filename, return:',++ systemPromptSpecifics,+ ].join('\n\n');++ const requireTags = availableCapabilities.some((capability) =>+ capability.documentInfoRequirements?.includes('tags'),+ );++ const userPrompt = JSON.stringify({+ document: {+ name: document?.originalName,+ content: document?.content,+ },+ ...(requireTags+ ? {+ existingTags: existingTags.map((tag) => ({+ name: tag.name,+ description: tag.description,+ })),+ }+ : {}),+ });++ const schemaEntries = promptContext.reduce<v.ObjectEntries>(+ (acc, { responseSchema }) => ({ ...acc, ...responseSchema.entries }),+ {},+ );++ const enrichmentResponse = await aiServices.generateStructuredData({modelId: ensureModelId(organizationSettings.ai.autoTagging.modelId),+ organizationId: document.organizationId,+ source: 'document-enrichment',+ schema: v.object(schemaEntries),+ systemPrompt,+ userPrompt,});- const durationMs = Date.now() - startedAt;- logger.info({ documentId, organizationId, durationMs }, 'Auto-tagging completed');- await applyAutoTaggingActions({ documentId, organizationId, ...actions });+ const enrichmentResults = await Promise.allSettled(+ promptContext.map(async ({ capability, responseSchema }) =>+ capability.apply({+ response: enrichmentResponse as v.InferOutput<typeof responseSchema>,+ documentId,+ organizationId,+ tags: existingTags,+ organizationSettings,+ }),+ ),+ );++ const failures = enrichmentResults.filter(+ (result): result is PromiseRejectedResult => result.status === 'rejected',+ );++ if (failures.length > 0) {+ logger.error(+ {+ documentId,+ organizationId,+ capabilities: availableCapabilities.map((capability) => capability.name),+ failures: failures.map((failure) => failure.reason),+ },+ 'One or more document enrichment capabilities failed to apply.',+ );++ throw new AggregateError(+ failures.map((failure) => failure.reason),+ 'One or more document enrichment capabilities failed to apply.',+ );+ }++ logger.info(+ {+ documentId,+ organizationId,+ capabilities: availableCapabilities.map((capability) => capability.name),+ },+ 'Document enrichment completed.',+ );};}diff --git a/apps/papra-server/src/modules/document-enrichment/enrichment-capabilities/enrichment-capabilities-definition.ts b/apps/papra-server/src/modules/document-enrichment/enrichment-capabilities/enrichment-capabilities-definition.tsnew file mode 100644index 00000000..c09347a5--- /dev/null+++ b/apps/papra-server/src/modules/document-enrichment/enrichment-capabilities/enrichment-capabilities-definition.ts@@ -0,0 +1,44 @@+import type { InferOutput } from 'valibot';+import type { OrganizationSettings } from '../../organizations/organization-settings/organization-settings.types';+import type { GenericObjectSchema } from '../../shared/schemas/objects.schemas';+import type { Tag } from '../../tags/tags.types';+import type { DocumentEnrichmentCapability } from '../document-enrichment.schemas';++export type DocumentEnrichmentCapabilityDefinition<+ Name extends string = string,+ ResponseSchema extends GenericObjectSchema = GenericObjectSchema,+> = {+ name: Name;++ isAvailable: (args: { organizationSettings: OrganizationSettings; tags: Tag[] }) => boolean;++ buildSystemPromptFragments: (args: {+ organizationSettings: OrganizationSettings;+ tags: Tag[];+ }) => {+ fragment: string;+ };++ getResponseSchema: (args: {+ organizationSettings: OrganizationSettings;+ tags: Tag[];+ }) => ResponseSchema;++ apply: (args: {+ documentId: string;+ organizationId: string;+ response: InferOutput<ResponseSchema>;+ organizationSettings: OrganizationSettings;+ tags: Tag[];+ }) => Promise<void>;++ documentInfoRequirements: ('tags' | 'custom-properties')[];+};++export function defineDocumentEnrichmentCapabilityFactory<+ FactoryArgs = unknown,+ Name extends DocumentEnrichmentCapability = DocumentEnrichmentCapability,+ ResponseSchema extends GenericObjectSchema = GenericObjectSchema,+>(factory: (args: FactoryArgs) => DocumentEnrichmentCapabilityDefinition<Name, ResponseSchema>) {+ return factory;+}diff --git a/apps/papra-server/src/modules/document-enrichment/enrichment-capabilities/tags/tags.enrichment-capability.ts b/apps/papra-server/src/modules/document-enrichment/enrichment-capabilities/tags/tags.enrichment-capability.tsnew file mode 100644index 00000000..c8795dc5--- /dev/null+++ b/apps/papra-server/src/modules/document-enrichment/enrichment-capabilities/tags/tags.enrichment-capability.ts@@ -0,0 +1,87 @@+import * as v from 'valibot';+import { defineDocumentEnrichmentCapabilityFactory } from '../enrichment-capabilities-definition';+import type { buildApplyAutoTaggingActions } from '../../../auto-tagging/auto-tagging.usecases';+import type { Config } from '../../../config/config.types';+import { getTagsActions } from '../../../auto-tagging/auto-tagging.models';++export const buildTagsEnrichmentCapability = defineDocumentEnrichmentCapabilityFactory(+ ({+ config,+ applyAutoTaggingActions,+ }: {+ config: Config;+ applyAutoTaggingActions: ReturnType<typeof buildApplyAutoTaggingActions>;+ }) => {+ return {+ name: 'auto-tagging',++ documentInfoRequirements: ['tags'],++ isAvailable: ({ organizationSettings, tags }) =>+ config.ai.isEnabled &&+ config.autoTagging.isEnabled &&+ organizationSettings.ai.autoTagging.isEnabled &&+ (organizationSettings.ai.autoTagging.canCreateNewTags || tags.length > 0),++ buildSystemPromptFragments: ({ organizationSettings }) => {+ const { canCreateNewTags, maxTags } = organizationSettings.ai.autoTagging;++ return {+ fragment: [+ 'DOCUMENT TAGS',+ '',+ '- Suggest tags that are relevant to the document content.',+ `- Select at most ${maxTags} tags.`,++ ...(canCreateNewTags+ ? [+ '- You may suggest new tags that do not exist yet.',+ '- If you suggest new tags, provide an optional description for each new tag.',+ '- Do not suggest new tags that are too similar to existing tags.',+ ]+ : [+ '- You may only suggest existing tags.',+ '- If no relevant tags can be found, return an empty list.',+ ]),+ ].join('\n'),+ };+ },++ getResponseSchema: ({ organizationSettings, tags }) => {+ const hasExistingTags = tags.length > 0;+ const { canCreateNewTags } = organizationSettings.ai.autoTagging;++ if (canCreateNewTags && hasExistingTags) {+ return v.object({+ existingTags: v.array(v.picklist(tags.map((tag) => tag.name))),+ newTags: v.array(v.object({ name: v.string(), description: v.optional(v.string()) })),+ });+ }++ if (canCreateNewTags && !hasExistingTags) {+ return v.object({+ newTags: v.array(v.object({ name: v.string(), description: v.optional(v.string()) })),+ });+ }++ return v.object({+ existingTags: v.array(v.picklist(tags.map((tag) => tag.name))),+ });+ },++ apply: async ({ response, documentId, organizationId, tags, organizationSettings }) => {+ const actions = getTagsActions({+ autoTaggingResponse: response,+ existingTags: tags,+ maxTags: organizationSettings.ai.autoTagging.maxTags,+ });++ await applyAutoTaggingActions({+ documentId,+ organizationId,+ ...actions,+ });+ },+ };+ },+);diff --git a/apps/papra-server/src/modules/document-enrichment/tasks/enrich-document.task.test.ts b/apps/papra-server/src/modules/document-enrichment/tasks/enrich-document.task.test.tsindex 76c1d79e..9c22c205 100644--- a/apps/papra-server/src/modules/document-enrichment/tasks/enrich-document.task.test.ts+++ b/apps/papra-server/src/modules/document-enrichment/tasks/enrich-document.task.test.ts@@ -114,7 +114,7 @@ describe('document enrichment task', () => {expect(request).toMatchObject({organizationId: 'org_1',modelId: 'openai://test-model',- source: 'auto-tagging',+ source: 'document-enrichment',});expect(request.userPrompt).toContain('Invoice for office supplies');expect(await deps.db.select().from(documentsTagsTable)).toEqual([diff --git a/apps/papra-server/src/modules/document-enrichment/tasks/enrich-document.task.ts b/apps/papra-server/src/modules/document-enrichment/tasks/enrich-document.task.tsindex 97cfc592..6da5488d 100644--- a/apps/papra-server/src/modules/document-enrichment/tasks/enrich-document.task.ts+++ b/apps/papra-server/src/modules/document-enrichment/tasks/enrich-document.task.ts@@ -1,10 +1,7 @@import type { Database } from '../../app/database/database.types';import type { TaskServices } from '../../tasks/tasks.services';import { createTagsRepository } from '../../tags/tags.repository';-import {- buildApplyAutoTaggingActions,- buildPromptForAutoTagging,-} from '../../auto-tagging/auto-tagging.usecases';+import { buildApplyAutoTaggingActions } from '../../auto-tagging/auto-tagging.usecases';import { applyTagsToDocuments, createTag } from '../../tags/tags.usecases';import { createLogger } from '../../shared/logger/logger';import { createResolveOrganizationSettingsUsecase } from '../../organizations/organization-settings/organization-settings.usecases';@@ -15,6 +12,7 @@ import type { EventServices } from '../../app/events/events.services';import type { AiServices } from '../../ai/ai.services';import { buildEnrichDocument } from '../document-enrichment.usecases';import type { DocumentEnrichmentCapability } from '../document-enrichment.schemas';+import { buildTagsEnrichmentCapability } from '../enrichment-capabilities/tags/tags.enrichment-capability';export async function registerEnrichDocumentTask({taskServices,@@ -54,16 +52,21 @@ export async function registerEnrichDocumentTask({documentsRepository,tagsRepository,logger,- promptForAutoTagging: buildPromptForAutoTagging({ aiServices }),- applyAutoTaggingActions: buildApplyAutoTaggingActions({- createTag: async (args) => createTag({ ...args, config, tagsRepository }),- applyTagsToDocuments: async (args) =>- applyTagsToDocuments({ ...args, tagsRepository, eventServices, logger }),- }),+ capabilityDefinitions: [+ buildTagsEnrichmentCapability({+ config,+ applyAutoTaggingActions: buildApplyAutoTaggingActions({+ createTag: async (args) => createTag({ ...args, config, tagsRepository }),+ applyTagsToDocuments: async (args) =>+ applyTagsToDocuments({ ...args, tagsRepository, eventServices, logger }),+ }),+ }),+ ],resolveOrganizationSettings: createResolveOrganizationSettingsUsecase({config,organizationSettingsRepository,}),+ aiServices,});await enrichDocument({ documentId, organizationId, capabilities });diff --git a/apps/papra-server/src/modules/shared/schemas/objects.schemas.ts b/apps/papra-server/src/modules/shared/schemas/objects.schemas.tsnew file mode 100644index 00000000..6969fea4--- /dev/null+++ b/apps/papra-server/src/modules/shared/schemas/objects.schemas.ts@@ -0,0 +1,3 @@+import type { ObjectSchema, StrictObjectSchema } from 'valibot';++export type GenericObjectSchema = ObjectSchema<any, any> | StrictObjectSchema<any, any>;