Guia passo a passo: adicionando funções de IA personalizadas ao agente de IA do ONLYOFFICE
Com nosso novo smart o agente IA, oferecemos ferramentas de ponta para atender às demandas do acelerado mundo digital de hoje. Como um projeto de código aberto, acolhemos a inovação orientada pelo usuário. Nesta publicação, mostraremos como adicionar funções personalizadas ao agente de IA, tornando seu trabalho com documentos mais rápido, fácil e conveniente.
O que são funções de IA e para que servem?
As funções de IA são os blocos de construção principais da funcionalidade de um agente de IA. Essencialmente, são instruções que informam ao agente de IA:
- Qual solicitação enviar ao modelo de IA.
- Quais manipulações realizar no seu documento.
Ao usar funções de IA, você pode estender e controlar como a IA interage com o conteúdo do seu documento.
Como usar uma função de IA
- Adicione um modelo de sua escolha ao plugin IA.
- Abra a caixa de diálogo do agente de IA pressionando CTRL + /.
- Digite seu prompt e pressione Enter.
Exemplo: a função commentText
A função commentText permite adicionar comentários gerados por IA diretamente ao seu documento. Veja como funciona:
- Selecione uma palavra sobre a qual deseja deixar um comentário
- Abra a caixa de diálogo do agente de IA (CTRL + /).
- Digite sua instrução, por exemplo: “Explique este texto”.
- Pressione Enter.
The AI agent will run the commentText function and insert relevant comments into your document:
Por que adicionar funções personalizadas ao seu agente de IA?
Adicionar funções de IA personalizadas permite expandir os recursos do agente de IA inteligente e adaptá-lo às suas necessidades específicas. Seja trabalhando com documentos, planilhas ou apresentações, a versatilidade do agente, combinada com o poder dos modelos de IA modernos, ajuda você a transformar ideias em realidade e integrá-las perfeitamente ao seu fluxo de trabalho.
Lógica geral de adição de função de IA personalizada
O processo de adição de uma função personalizada envolve duas fases principais:
- Registro de Função – Registra a função de IA e seus metadados no ambiente do agente.
- Execução de Função – Implementa a lógica principal, que inclui o envio de solicitações ao modelo de IA e a manipulação do conteúdo do documento usando nosso Office API.
Agora vamos dar uma olhada mais de perto nessas fases.
Registro de função
Para adicionar uma nova função, implementamos o objeto RegisteredFunction. Ele nos permite adicionar metadados e lógica. Aqui está um exemplo de como adicionar a função commentText para Document Editor:
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\"}"
]
Onde:
- func.name: o nome que a IA usará para chamar esta função (por exemplo, “commentText”).
- func.params: uma lista de parâmetros que a função espera da IA. Por exemplo:
– prompt (string): uma descrição ou instrução para o comentário.
– type (string): “comentário” ou “nota de rodapé” — especifica o que inserir.
- func.examples: exemplos de chamadas de função corretas para a IA.
- func.description: explica à IA para que serve a função.
Esses parâmetros são usados pela IA. O RegisteredFunction() objeto é definido no arquivo helperFunc.js .
Lógica de execução de função
Depois de registrar a função, implementamos a lógica real que é executada quando a IA chama essa função.
- Recupere o texto selecionado 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;
});
- Construa o prompt para a IA combinando params.prompt e o texto selecionado.
let argPromt = params.prompt + ":\n" + text;
- Inicialize o objeto AI.Request.create usando AI.Request.create. O objeto é definido no arquivo engine.js . Este objeto facilita o envio de uma solicitação ao 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;
- Envie a solicitação usando chatRequest() e receba o resultado em um retorno de chamada.
// 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;
- Insira a resposta como um comentário ou nota de rodapé usando AddFootnote() ou AddComment()
Implementação 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);
});
Implementação 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;
});
});
}
Nota!
Para garantir que todo o bloco de alterações possa ser revertido após a execução da solicitação, usamos StartAction e EndAction métodos na função commentText.
Toda a implementação da função commentText com comentários:
(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 em acompanhar o ritmo da tecnologia moderna, garantindo que nosso agente de IA inteligente continue a evoluir junto com as necessidades do mundo digital atual. Ao criar suas próprias funções personalizadas, você pode expandir seus recursos para atender às suas necessidades específicas e exclusivas. Agradecemos sua criatividade e ideias.
Se tiver alguma dúvida, sugestão ou feedback, entre em contato conosco. Estamos sempre prontos para colaborar e ajudar você a concretizar sua visão! Boa sorte em seus empreendimentos exploratórios!
Crie sua conta gratuita no ONLYOFFICE
Visualize, edite e colabore em documentos, planilhas, slides, formulários e arquivos PDF online.