fixup! ️(frontend) improve prompt of some actions

This commit is contained in:
Anthony LC
2026-01-27 17:53:20 +01:00
parent 79b86b069b
commit b6b0748ab3
3 changed files with 130 additions and 134 deletions
@@ -1,5 +1,5 @@
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
import { createAIExtension, llmFormats } from '@blocknote/xl-ai';
import { createAIExtension } from '@blocknote/xl-ai';
import { useMemo } from 'react';
import { baseApiUrl, fetchAPI } from '@/api';
@@ -38,7 +38,7 @@ export const useAI = (docId: Doc['id'], aiAllowed: boolean) => {
stream: conf.AI_STREAM,
model,
agentCursor: conf?.AI_BOT,
promptBuilder: promptBuilder(llmFormats.html.defaultPromptBuilder),
promptBuilder,
});
return extension;
@@ -1,4 +1,5 @@
import { Block } from '@blocknote/core';
import { llmFormats } from '@blocknote/xl-ai';
import { CoreMessage } from 'ai';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,11 +14,6 @@ export type PromptBuilderInput = {
previousMessages?: Array<CoreMessage>;
};
type PromptBuilder = (
editor: DocsBlockNoteEditor,
opts: PromptBuilderInput,
) => Promise<Array<CoreMessage>>;
/**
* Custom implementation of the PromptBuilder that allows for using predefined prompts.
*
@@ -28,131 +24,131 @@ export const usePromptAI = () => {
const { t } = useTranslation();
return useCallback(
(defaultPromptBuilder: PromptBuilder) =>
async (
editor: DocsBlockNoteEditor,
opts: PromptBuilderInput,
): Promise<Array<CoreMessage>> => {
const systemPrompts: Record<
| 'add-edit-instruction'
| 'add-formatting'
| 'add-markdown'
| 'assistant'
| 'language'
| 'referenceId',
CoreMessage
> = {
assistant: {
role: 'system',
content: t(`You are an AI assistant that edits user documents.`),
},
referenceId: {
role: 'system',
content: t(
`Keep block IDs exactly as provided when referencing them (including the trailing "$").`,
),
},
'add-markdown': {
role: 'system',
content: t(`Answer the user prompt in markdown format.`),
},
'add-formatting': {
role: 'system',
content: t(`Add formatting to the text to make it more readable.`),
},
'add-edit-instruction': {
role: 'system',
content: t(
`Add content; do not delete or alter existing blocks unless explicitly told.`,
),
},
language: {
role: 'system',
content: t(
`Detect the dominant language inside the provided blocks. YOU MUST PROVIDE A ANSWER IN THE DETECTED LANGUAGE.`,
),
},
};
async (
editor: DocsBlockNoteEditor,
opts: PromptBuilderInput,
): Promise<Array<CoreMessage>> => {
const systemPrompts: Record<
| 'add-edit-instruction'
| 'add-formatting'
| 'add-markdown'
| 'assistant'
| 'language'
| 'referenceId',
CoreMessage
> = {
assistant: {
role: 'system',
content: t(`You are an AI assistant that edits user documents.`),
},
referenceId: {
role: 'system',
content: t(
`Keep block IDs exactly as provided when referencing them (including the trailing "$").`,
),
},
'add-markdown': {
role: 'system',
content: t(`Answer the user prompt in markdown format.`),
},
'add-formatting': {
role: 'system',
content: t(`Add formatting to the text to make it more readable.`),
},
'add-edit-instruction': {
role: 'system',
content: t(
`Add content; do not delete or alter existing blocks unless explicitly told.`,
),
},
language: {
role: 'system',
content: t(
`Detect the dominant language inside the provided blocks. YOU MUST PROVIDE AN ANSWER IN THE DETECTED LANGUAGE.`,
),
},
};
const userPrompts: Record<string, string> = {
'continue writing': t(
'Keep writing about the content send in the prompt, expanding on the ideas.',
),
'improve writing': t(
'Improve the writing of the selected text. Make it more professional and clear.',
),
summarize: t('Summarize the document into a concise paragraph.'),
'fix spelling': t(
'Fix the spelling and grammar mistakes in the selected text.',
),
};
const userPrompts: Record<string, string> = {
'continue writing': t(
'Keep writing about the content sent in the prompt, expanding on the ideas.',
),
'improve writing': t(
'Improve the writing of the selected text. Make it more professional and clear.',
),
summarize: t('Summarize the document into a concise paragraph.'),
'fix spelling': t(
'Fix the spelling and grammar mistakes in the selected text.',
),
};
// Modify userPrompt if it matches a custom prompt
const customPromptMatch = opts.userPrompt.match(/^([^:]+)(?=[:]|$)/);
let modifiedOpts = opts;
const promptKey = customPromptMatch?.[0].trim().toLowerCase();
if (promptKey) {
if (userPrompts[promptKey]) {
modifiedOpts = {
...opts,
userPrompt: userPrompts[promptKey],
};
}
// Modify userPrompt if it matches a custom prompt
const customPromptMatch = opts.userPrompt.match(/^([^:]+)(?=[:]|$)/);
let modifiedOpts = opts;
const promptKey = customPromptMatch?.[0].trim().toLowerCase();
if (promptKey) {
if (userPrompts[promptKey]) {
modifiedOpts = {
...opts,
userPrompt: userPrompts[promptKey],
};
}
let prompts = await defaultPromptBuilder(editor, modifiedOpts);
const isTransformExistingContent = !!opts.selectedBlocks?.length;
if (!isTransformExistingContent) {
prompts = prompts.map((prompt) => {
if (!prompt.content || typeof prompt.content !== 'string') {
return prompt;
}
/**
* Fix a bug when the initial content is empty
* TODO: Remove this when the bug is fixed in BlockNote
*/
if (prompt.content === '[]') {
const lastBlockId =
editor.document[editor.document.length - 1].id;
prompt.content = `[{\"id\":\"${lastBlockId}$\",\"block\":\"<p></p>\"}]`;
return prompt;
}
if (
prompt.content.includes(
"You're manipulating a text document using HTML blocks.",
)
) {
prompt = systemPrompts['add-markdown'];
return prompt;
}
if (
prompt.content.includes(
'First, determine what part of the document the user is talking about.',
)
) {
prompt = systemPrompts['add-edit-instruction'];
}
}
let prompts = await llmFormats.html.defaultPromptBuilder(
editor,
modifiedOpts,
);
const isTransformExistingContent = !!opts.selectedBlocks?.length;
if (!isTransformExistingContent) {
prompts = prompts.map((prompt) => {
if (!prompt.content || typeof prompt.content !== 'string') {
return prompt;
});
}
prompts.push(systemPrompts['add-formatting']);
}
/**
* Fix a bug when the initial content is empty
* TODO: Remove this when the bug is fixed in BlockNote
*/
if (prompt.content === '[]') {
const lastBlockId = editor.document[editor.document.length - 1].id;
prompts.unshift(systemPrompts['assistant']);
prompts.push(systemPrompts['referenceId']);
prompt.content = `[{\"id\":\"${lastBlockId}$\",\"block\":\"<p></p>\"}]`;
return prompt;
}
// Try to keep the language of the document except when we are translating
if (!promptKey?.includes('Translate into')) {
prompts.push(systemPrompts['language']);
}
if (
prompt.content.includes(
"You're manipulating a text document using HTML blocks.",
)
) {
prompt = systemPrompts['add-markdown'];
return prompt;
}
return prompts;
},
if (
prompt.content.includes(
'First, determine what part of the document the user is talking about.',
)
) {
prompt = systemPrompts['add-edit-instruction'];
}
return prompt;
});
prompts.push(systemPrompts['add-formatting']);
}
prompts.unshift(systemPrompts['assistant']);
prompts.push(systemPrompts['referenceId']);
// Try to keep the language of the document except when we are translating
if (!promptKey?.includes('Translate into')) {
prompts.push(systemPrompts['language']);
}
return prompts;
},
[t],
);
};
@@ -967,16 +967,16 @@
"Warning": "Attention",
"Why you can't edit the document?": "Pourquoi vous ne pouvez pas modifier le document ?",
"Write": "Écrire",
"You are an AI assistant that helps users to edit their documents.": "Vous êtes un assistant IA qui aide les utilisateurs à éditer leurs documents.",
"Answer the user prompt in markdown format.": "Répondez à la demande de l'utilisateur au format markdown.",
"Add formatting to the text to make it more readable.": "Ajoutez du formatage au texte pour le rendre plus lisible.",
"Keep adding to the document, do not delete or modify existing blocks.": "Continuez à ajouter au document, ne supprimez ni ne modifiez les blocs existants.",
"Your answer must be in the same language as the document.": "Votre réponse doit être dans la même langue que le document.",
"Fix the spelling and grammar mistakes in the selected text.": "Corrigez les fautes d'orthographe et de grammaire dans le texte sélectionné.",
"Improve the writing of the selected text. Make it more professional and clear.": "Améliorez l'écriture du texte sélectionné. Rendez-le plus professionnel et clair.",
"Summarize the document into a concise paragraph.": "Résumez le document en un paragraphe concis.",
"Keep writing about the content send in the prompt, expanding on the ideas.": "Continuez à écrire sur le contenu envoyé dans la demande, en développant les idées.",
"Important, verified the language of the document! Your answer MUST be in the same language as the document. If the document is in English, your answer MUST be in English. If the document is in Spanish, your answer MUST be in Spanish, etc.": "Important, vérifiez la langue du document ! Votre réponse DOIT être dans la même langue que le document. Si le document est en anglais, votre réponse DOIT être en anglais. Si le document est en espagnol, votre réponse DOIT être en espagnol, etc.",
"You are an AI assistant that helps users to edit their documents.": "Tu es un assistant IA qui aide les utilisateurs à éditer leurs documents.",
"Answer the user prompt in markdown format.": "Réponds à la demande de l'utilisateur au format markdown.",
"Add formatting to the text to make it more readable.": "Ajoute du formatage au texte pour le rendre plus lisible.",
"Keep adding to the document, do not delete or modify existing blocks.": "Continue d'ajouter au document, ne supprime ni ne modifie les blocs existants.",
"Your answer must be in the same language as the document.": "Ta réponse doit être dans la même langue que le document.",
"Fix the spelling and grammar mistakes in the selected text.": "Corrige les fautes d'orthographe et de grammaire dans le texte sélectionné.",
"Improve the writing of the selected text. Make it more professional and clear.": "Améliore l'écriture du texte sélectionné. Rends-le plus professionnel et clair.",
"Summarize the document into a concise paragraph.": "Résume le document en un paragraphe concis.",
"Keep writing about the content sent in the prompt, expanding on the ideas.": "Continue à écrire sur le contenu envoyé dans la demande, en développant les idées.",
"Important, verified the language of the document! Your answer MUST be in the same language as the document. If the document is in English, your answer MUST be in English. If the document is in Spanish, your answer MUST be in Spanish, etc.": "Important, vérifie la langue du document ! Ta réponse DOIT être dans la même langue que le document. Si le document est en anglais, ta réponse DOIT être en anglais. Si le document est en espagnol, ta réponse DOIT être en espagnol, etc.",
"You are the sole owner of this group, make another member the group owner before you can change your own role or be removed from your document.": "Vous êtes le seul propriétaire de ce groupe, faites d'un autre membre le propriétaire du groupe, avant de pouvoir modifier votre propre rôle ou vous supprimer du document.",
"You can view this document but need additional access to see its members or modify settings.": "Vous pouvez voir ce document mais vous avez besoin d'un accès supplémentaire pour voir ses membres ou modifier les paramètres.",
"You cannot restrict access to a subpage relative to its parent page.": "Vous ne pouvez pas restreindre l'accès à une sous-page par rapport à sa page parente.",