Guide étape par étape : ajouter des fonctions IA personnalisées à l’agent IA ONLYOFFICE

20 août 2025Par Dasha

Grâce à notre nouvel agent IA, nous proposons des outils de pointe pour répondre aux exigences du monde numérique en constante évolution. En tant que projet open source, nous encourageons l’innovation axée sur les utilisateurs. Dans cet article, nous vous montrerons comment ajouter des fonctions personnalisées à l’agent IA afin de rendre votre travail avec les documents plus rapide, plus facile et plus pratique.

Step-by-step guide: adding custom AI functions to ONLYOFFICE AI agent

Que sont les fonctions IA et à quoi elles servent

Les fonctions IA sont les éléments constitutifs fondamentaux des fonctionnalités d’un agent IA. Il s’agit essentiellement d’instructions qui indiquent à l’agent IA :

  • Quelle requête envoyer au modèle IA.
  • Quelles manipulations effectuer sur votre document.

En utilisant les fonctions IA, vous pouvez étendre et contrôler la manière dont l’IA interagit avec le contenu de votre document.

Comment utiliser une fonction IA

  1. Ajoutez le modèle de votre choix au plugin IA.
  2. Ouvrez la boîte de dialogue de l’agent IA avec Ctrl + / (pour AZERTY Ctrl + Shift + /).
  3. Saisissez votre invite et appuyez sur Entrée.

Exemple : la fonction commentText

La fonction commentText vous permet d’ajouter des commentaires générés par l’IA directement dans votre document. Voici comment cela fonctionne :

  • Sélectionnez un mot sur lequel vous souhaitez laisser un commentaire.
  • Ouvrez la boîte de dialogue de l’agent IA.
  • Saisissez votre instruction, par exemple : « Expliquez ce texte ».
  • Appuyez sur Entrée.

Step-by-step guide: adding custom AI functions to ONLYOFFICE AI agent

L’agent IA exécutera la fonction commentText et insérera les commentaires pertinents dans votre document :

Step-by-step guide: adding custom AI functions to ONLYOFFICE AI agent

Pourquoi ajouter des fonctions personnalisées à votre agent IA ?

L’ajout de fonctions IA personnalisées vous permet d’étendre les capacités de l’agent IA intelligent et de l’adapter à vos besoins précis. Que vous travailliez avec des documents, des feuilles de calcul ou des présentations, la polyvalence de l’agent, combinée à la puissance des modèles IA modernes, vous aide à concrétiser vos idées et à les intégrer de manière transparente dans votre flux de travail.

Logique générale de l’ajout d’une fonction IA personnalisée

Le processus d’ajout d’une fonction personnalisée comprend deux phases principales :

  • Enregistrement de la fonction : enregistre la fonction IA et ses métadonnées dans l’environnement de l’agent.
  • Exécution de la fonction : met en œuvre la logique de base, qui comprend l’envoi de requêtes au modèle IA et la manipulation du contenu des documents à l’aide de notre API Office.

Examinons maintenant ces phases plus en détail.

Enregistrement d’une fonction

Pour ajouter une nouvelle fonction, nous implémentons l’objet RegisteredFunction. Il nous permet d’ajouter des métadonnées et une logique. Voici un exemple d’ajout de la fonction commentText pour l’éditeur de documents :

let func = new RegisteredFunction();
        func.name = "commentText";
        func.params = [
            "type (string): whether to add as a 'comment' or as a 'footnote'    default is 'comment')"
        ];


        func.examples = [
            "If you need to explain selected text as a comment, respond with:\n" +
            "[functionCalling (commentText)]: {\"prompt\" : \"Explain this text\", \"type\": \"comment\"}",


            "If you need to add a footnote to selected text, respond with:\n" +
            "[functionCalling (commentText)]: {\"prompt\" : \"Add a footnote to this text\", \"type\": \"footnote\"}",


            "If you need to comment selected text, respond with:\n" +
            "[functionCalling (commentText)]: {\"prompt\" : \"Comment this text\"}",


            "If you need to explain selected text as a footnote, respond with:\n" +
            "[functionCalling (commentText)]: {\"prompt\" : \"Explain this text\", \"type\": \"footnote\"}"
     ]

Où :

  • func.name: le nom que l’IA utilisera pour appeler cette fonction (par exemple, « commentText »).
  • func.params: une liste des paramètres que la fonction attend de l’IA. Par exemple :

 prompt (string) : une description ou une instruction pour le commentaire.

–  type (string) : « comment » ou « footnote » — spécifie ce qu’il faut insérer.

  •  func.examples : exemples d’appels de fonction corrects pour l’IA.
  • func.description : explique à l’IA à quoi sert la fonction.

Ces paramètres sont utilisés par l’IA. L’objet RegisteredFunction() est défini dans le fichier helperFunc.js.

Logique d’exécution de la fonction

Après avoir enregistré la fonction, nous implémentons la logique réelle qui sera exécutée lorsque l’IA appellera cette fonction.

  • Récupérez le texte sélectionné à l’aide de Asc.Editor.callCommand().
func.call = async function(params) {
            let type = params.type;
            let isFootnote = "footnote" === type;


// Executes a block of code inside the editor's context using the office=js API.
            let text = await Asc.Editor.callCommand(function(){
                let doc = Api.GetDocument();
// Gets the current selected text range.
                let range = doc.GetRangeBySelect();
                let text = range ? range.GetText() : "";
                if (!text)
                {
                    text = doc.GetCurrentWord();
// Selects the current word so comments can be applied to it.
                    doc.SelectCurrentWord();
                }


                return text;
            });
  • Construisez l’invite pour l’IA en combinant params.prompt et le texte sélectionné.
let argPromt = params.prompt + ":\n" + text;
  • Initialisez l’objet AI.Request.create à l’aide de AI.Request.create. L’objet est défini dans le fichier engine.js. Cet objet facilite l’envoi d’une requête au modèle d’IA.
// Initializes a request engine for communicating with the AI model (e.g. Chat, Translation).
            let requestEngine = AI.Request.create(AI.ActionType.Chat);
            if (!requestEngine)
                return;
  • Envoyez la requête à l’aide de chatRequest() et recevez le résultat dans un rappel.
// Sends a prompt to the AI model and processes the response via callback. Can stream or wait.
                let result = await requestEngine.chatRequest(argPromt, false, async function(data) {
                    if (!data)
                        return;
  • Insérez la réponse sous forme de commentaire ou de note de bas de page à l’aide de AddFootnote() ou AddComment().

Implémentation d’AddFootnote :

if (isFootnote)
            {
                let addFootnote = true;
// Sends a prompt to the AI model and processes the response via callback. Can stream or wait.
                let result = await requestEngine.chatRequest(argPromt, false, async function(data) {
                    if (!data)
                        return;


// Marks the end of a logical group or block action in the editor.
                    await checkEndAction();
                    Asc.scope.data = data;
                    Asc.scope.model = requestEngine.modelUI.name;


                    if (addFootnote)
                    {
// Executes a block of code inside the editor's context using the document model API.
                        await Asc.Editor.callCommand(function(){
// Returns the main document object, which gives access to all editing, structure, and selection APIs.
                            Api.GetDocument().AddFootnote();
                        });
                        addFootnote = false;
                    }
// Inserts the AI-generated result into the document at the current selection or cursor.
                    await Asc.Library.PasteText(data);
                });

Implémentation d’AddComment :

let commentId = null;
// Sends a prompt to the AI model and processes the response via callback. Can stream or wait.
                let result = await requestEngine.chatRequest(argPromt, false, async function(data) {
                    if (!data)
                        return;


// Marks the end of a logical group or block action in the editor.
                    await checkEndAction();
                    Asc.scope.data = data;
                    Asc.scope.model = requestEngine.modelUI.name;
                    Asc.scope.commentId = commentId;


// Executes a block of code inside the editor's context using the document model API.
                    commentId = await Asc.Editor.callCommand(function(){
// Returns the main document object, which gives access to all editing, structure, and selection APIs.
                        let doc = Api.GetDocument();


                        let commentId = Asc.scope.commentId;
                        if (!commentId)
                        {
// Gets the current selected text range, which can be modified or annotated.
                            let range = doc.GetRangeBySelect();
                            if (!range)
                                return null;


                            let comment = range.AddComment(Asc.scope.data, Asc.scope.model, "uid" + Asc.scope.model);
                            if (!comment)
                                return null;
                            doc.ShowComment([comment.GetId()]);
                            return comment.GetId();
                        }


                        let comment = doc.GetCommentById(commentId);
                        if (!comment)
                            return commentId;


                        comment.SetText(comment.GetText() + scope.data);
                        return commentId;
                    });
                });
            }

Remarque !

Pour garantir que l’ensemble des modifications puisse être annulé après l’exécution de la requête, nous utilisons les méthodes StartAction et EndAction dans la fonction commentText.

Implémentation complète de la fonction commentText avec commentaires :

(function(){
// Defines the commentText function — lets AI insert a comment or footnote for selected text using AI response.
    WORD_FUNCTIONS.commentText = function()
    {
// Creates a new function object that will be registered and exposed to the AI.
        let func = new RegisteredFunction();
        func.name = "commentText";
// Lists the parameters expected by the function. These are passed as a JSON object by the AI agent.
        func.params = [
            "type (string): whether to add as a 'comment' or as a 'footnote' (default is 'comment')"
        ];


// Gives example JSON inputs to teach the AI how to correctly invoke this function.
        func.examples = [
            "If you need to explain selected text as a comment, respond with:\n" +
            "[functionCalling (commentText)]: {\"prompt\" : \"Explain this text\", \"type\": \"comment\"}",


            "If you need to add a footnote to selected text, respond with:\n" +
            "[functionCalling (commentText)]: {\"prompt\" : \"Add a footnote to this text\", \"type\": \"footnote\"}",


            "If you need to comment selected text, respond with:\n" +
            "[functionCalling (commentText)]: {\"prompt\" : \"Comment this text\"}",


            "If you need to explain selected text as a footnote, respond with:\n" +
            "[functionCalling (commentText)]: {\"prompt\" : \"Explain this text\", \"type\": \"footnote\"}"
        ];
        
// The actual logic that gets executed when the AI calls this function.
        func.call = async function(params) {
            let type = params.type;
            let isFootnote = "footnote" === type;


// Executes a block of code inside the editor's context using the office-js API.
            let text = await Asc.Editor.callCommand(function(){
                let doc = Api.GetDocument();
// Gets the current selected text range.
                let range = doc.GetRangeBySelect();
                let text = range ? range.GetText() : "";
                if (!text)
                {
                    text = doc.GetCurrentWord();
// Selects the current word so comments can be applied to it.
                    doc.SelectCurrentWord();
                }


                return text;
            });


            let argPromt = params.prompt + ":\n" + text;


// Initializes a request engine for communicating with the AI model (e.g. Chat, Translation).
            let requestEngine = AI.Request.create(AI.ActionType.Chat);
            if (!requestEngine)
                return;


            let isSendedEndLongAction = false;
// Marks the end of a logical group or block action in the editor.
            async function checkEndAction() {
                if (!isSendedEndLongAction) {
// Marks the end of a logical group or block action in the editor.
                    await Asc.Editor.callMethod("EndAction", ["Block", "AI (" + requestEngine.modelUI.name + ")"]);
                    isSendedEndLongAction = true
                }
            }


// Starts a block action in the editor, used for undo/redo 
            await Asc.Editor.callMethod("StartAction", ["Block", "AI (" + requestEngine.modelUI.name + ")"]);
// Starts a block action in the editor, used for undo/redo
            await Asc.Editor.callMethod("StartAction", ["GroupActions"]);


            if (isFootnote)
            {
                let addFootnote = true;
// Sends a prompt to the AI model and processes the response via callback
                let result = await requestEngine.chatRequest(argPromt, false, async function(data) {
                    if (!data)
                        return;


// Marks the end of a block action in the editor.
                    await checkEndAction();
                    Asc.scope.data = data;
                    Asc.scope.model = requestEngine.modelUI.name;


                    if (addFootnote)
                    {
// Executes a block of code inside the editor's context using the  office-js API.
                        await Asc.Editor.callCommand(function(){
                            Api.GetDocument().AddFootnote();
                        });
                        addFootnote = false;
                    }
// Inserts the AI-generated result into the document at the current selection or cursor.
                    await Asc.Library.PasteText(data);
                });
            }
            else 
            {
                let commentId = null;
// Sends a prompt to the AI model and processes the response via callback.
                let result = await requestEngine.chatRequest(argPromt, false, async function(data) {
                    if (!data)
                        return;


// Marks the end of a block action in the editor.
                    await checkEndAction();
                    Asc.scope.data = data;
                    Asc.scope.model = requestEngine.modelUI.name;
                    Asc.scope.commentId = commentId;


// Executes a block of code inside the editor's context using the office-js API.
                    commentId = await Asc.Editor.callCommand(function(){
                        let doc = Api.GetDocument();


                        let commentId = Asc.scope.commentId;
                        if (!commentId)
                        {
// Gets the current selected text range.
                            let range = doc.GetRangeBySelect();
                            if (!range)
                                return null;


                            let comment = range.AddComment(Asc.scope.data, Asc.scope.model, "uid" + Asc.scope.model);
                            if (!comment)
                                return null;
                            doc.ShowComment([comment.GetId()]);
                            return comment.GetId();
                        }


                        let comment = doc.GetCommentById(commentId);
                        if (!comment)
                            return commentId;


                        comment.SetText(comment.GetText() + scope.data);
                        return commentId;
                    });
                });
            }


// Marks the end of a  block action in the editor.
            await checkEndAction();
// Marks the end of a block action in the editor.
            await Asc.Editor.callMethod("EndAction", ["GroupActions"]);
        };


        return func;
    }

Nous nous engageons à rester à la pointe de la technologie moderne, en veillant à ce que notre agent IA intelligent continue d’évoluer en fonction des besoins du monde numérique actuel. En créant vos propres fonctions personnalisées, vous pouvez étendre ses capacités afin qu’elles répondent précisément à vos besoins spécifiques. Nous encourageons votre créativité et vos idées.

Si vous avez des questions, des suggestions ou des commentaires, n’hésitez pas à nous contacter. Nous sommes toujours prêts à collaborer et à vous aider à concrétiser votre vision ! Bonne chance dans vos projets exploratoires !

Créez votre compte ONLYOFFICE gratuit

Affichez, modifiez et coéditez des documents texte, feuilles de calcul, diapositives, formulaires et fichiers PDF en ligne.