Guía paso a paso: cómo añadir funciones de IA personalizadas al agente de IA de ONLYOFFICE
Con nuestro nuevo y avanzado agente de IA, ofrecemos herramientas de vanguardia para satisfacer las demandas del mundo digital actual. Como un proyecto de código abierto, damos la bienvenida a la innovación impulsada por los usuarios. En esta publicación, te mostraremos cómo añadir funciones personalizadas al agente de IA para hacer tu trabajo con documentos más rápido, fácil y conveniente.
¿Qué son las funciones de IA y para qué sirven?
Las funciones de IA son los bloques fundamentales de la funcionalidad del agente de IA. Esencialmente, son instrucciones que le dicen al agente de IA:
- Qué solicitud enviar al modelo de IA.
- Qué manipulaciones realizar en tu documento.
Al usar funciones de IA, puedes ampliar y controlar cómo la IA interactúa con el contenido de tus documentos.
Cómo usar una función de IA
- Añade un modelo de tu elección al plugin de IA.
- Abre el cuadro de diálogo del agente de IA presionando CTRL + B.
- Escribe tu solicitud y presiona Enter.
Ejemplo: la función commentText
La función commentText te permite añadir comentarios generados por IA directamente en tu documento. Así es como funciona:
- Selecciona una palabra sobre la que quieras dejar un comentario.
- Abre el cuadro de diálogo del agente de IA (CTRL + B).
- Escribe tu instrucción, por ejemplo: “Explica este texto.”
- Presiona Enter.
El agente de IA ejecutará la función commentText e insertará comentarios relevantes en tu documento:
¿Por qué añadir funciones personalizadas al agente de IA?
Añadir funciones de IA personalizadas te permite ampliar las capacidades del agente inteligente y adaptarlo a tus necesidades específicas. Ya sea que trabajes con documentos, hojas de cálculo o presentaciones, la versatilidad del agente, combinada con el poder de los modelos de IA modernos, te ayuda a convertir ideas en realidad e integrarlas sin problemas en tu flujo de trabajo.
Lógica general para añadir una función de IA personalizada
El proceso de añadir una función personalizada implica dos fases principales:
- Registro de la función – Registra la función de IA y sus metadatos dentro del entorno del agente.
- Ejecución de la función – Implementa la lógica principal, que incluye enviar solicitudes al modelo de IA y manipular el contenido del documento usando nuestra API de Office.
Ahora echemos un vistazo más detallado a estas fases.
Registro de funciones
Para añadir una nueva función, implementamos el objeto RegisteredFunction. Este objeto nos permite añadir tanto metadatos como la lógica de la función. A continuación, se muestra un ejemplo de cómo añadir la función commentText para el Editor de documentos:
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\"}"
]
¿Qué significa cada parámetro?
- func.name: el nombre que la IA usará para llamar a esta función (por ejemplo, “commentText”).
- func.params: una lista de parámetros que la función espera recibir de la IA. Por ejemplo:
– prompt (string): una descripción o instrucción para el comentario.
– type (string): “comment” o “footnote” — especifica qué se debe insertar.
- func.examples: ejemplos de llamadas correctas a la función para que la IA los aprenda.
- func.description: explica a la IA para qué sirve esta función.
Estos parámetros son utilizados por la IA para entender cómo usar la función. El objeto RegisteredFunction() está definido en el archivo helperFunc.js.
Lógica de ejecución de funciones
Después de registrar la función, implementamos la lógica que se ejecutará cuando la IA la llame.
- Obtén el texto seleccionado usando 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;
});
- Construye el prompt para la IA combinando params.prompt con el texto seleccionado.
let argPromt = params.prompt + ":\n" + text;
- Inicializa el objeto AI.Request.create, definido en el archivo engine.js. Este objeto se utiliza para enviar la solicitud al modelo de 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;
- Envía la solicitud utilizando chatRequest() y recibe el resultado mediante un callback (función de retorno).
// 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;
- Inserta la respuesta como comentario o nota al pie utilizando AddComment() o AddFootnote().
Implementación de 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);
});
Implementación de 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;
});
});
}
¡Ojo!
Para asegurarnos de que todo el bloque de cambios pueda deshacerse tras la ejecución, utilizamos los métodos StartAction y EndAction alrededor de la función commentText.
Implementación completa:
(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;
}
Estamos comprometidos con mantenernos al ritmo de la tecnología moderna, asegurando que nuestro agente inteligente de IA siga evolucionando junto con las necesidades del mundo digital actual. Al crear tus propias funciones personalizadas, puedes ampliar sus capacidades para adaptarlas exactamente a tus necesidades. Damos la bienvenida a tu creatividad e ideas.
Si tienes preguntas, sugerencias o comentarios, no dudes en contactarnos. ¡Siempre estamos listos para colaborar y ayudarte a hacer realidad tu visión! ¡Mucho éxito en tus proyectos exploratorios!
Crea tu cuenta gratuita de ONLYOFFICE
Visualiza, edita y colabora en documentos, hojas, diapositivas, formularios y archivos PDF en línea.