AI Agents

Add artificial intelligence capabilities to your Appivo applications

AI Agents Guide

Learn how to leverage Appivo's AI agent system to add artificial intelligence capabilities to your applications.

What Are AI Agents?

Appivo includes a powerful AI agent system that enables you to add artificial intelligence capabilities to your applications. AI agents can help with:

  • Code generation
  • Data analysis
  • Content processing
  • Text translation
  • Media transcription
  • Smart search and responses

Pre-Built Agents

Appivo provides 23 pre-built agents that you can use immediately in your applications.

Code Assistance Agents

AgentPurpose
generate-codeGenerates JavaScript code for actions following Appivo patterns
frontend-code-analyzerAnalyzes code for security, performance, and best practices

Data Processing Agents

AgentPurpose
generate-data-modelAutomates creation of Appivo data models
generate-queryCreates optimized database queries

Content Processing Agents

AgentPurpose
clean-htmlCleans and sanitizes HTML content
extract-keywordsExtracts keywords from text
translateTranslates content between languages
transcribe-audioTranscribes audio files to text
transcribe-imageExtracts text from images (OCR)
generate-responseGenerates contextual responses

Calling AI Agents

How you access AI agents depends on where you're working:

ContextMethod
Server-side (Action Scripts)context.getAIFunctions().invokeAgent()
Client-side (UI)AiButton widget
Custom Client IntegrationServer action proxy

From Server-Side Actions

In action scripts running on the server, use the AIFunctions API:

'use strict';
exports.execute = async function(context, params) {
    try {
        // Get the AIFunctions API
        const aiFunctions = context.getAIFunctions();

        // Call an AI agent
        const aiResult = await aiFunctions.invokeAgent('agent-name', {
            arguments: {
                instructions: params.userRequest,
                data: params.inputData
            }
        });

        // Process the AI result
        if (aiResult.success) {
            return {
                success: true,
                data: aiResult.result
            };
        }

        return {
            success: false,
            error: aiResult.error
        };

    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
};

Advanced Server-Side Options

The invokeAgent method supports additional options:

const aiFunctions = context.getAIFunctions();
const result = await aiFunctions.invokeAgent('agent-name', {
    arguments: {
        // Your agent-specific arguments
        query: 'user question',
        data: someData
    },
    history: [
        // Optional: Include chat history for context
        { role: 'user', message: 'previous question' },
        { role: 'ai', message: 'previous response' }
    ],
    disableTools: ['webSearch', 'fileAccess'], // Optional: Disable specific tools
    prompts: { // Optional: Override prompts
        system: 'Custom system prompt',
        user: 'Custom user prompt template'
    }
});

From Client-Side UI

In your views, use the AiButton widget to provide AI capabilities:

<aibutton
    :agent="'generate-data-model'"
    :onresult="handleAiResult"
    :onask="showLoadingState">
</aibutton>
methods: {
    handleAiResult: function(data) {
        // Process the AI-generated result
        console.log('AI generated:', data);
        this.processGeneratedModel(data);
    },
    showLoadingState: function() {
        this.isProcessing = true;
    }
}

Custom Client-Side Integration

For custom UI implementations, create a server action as a proxy:

Step 1: Create a server action

// Action: InvokeAIAgent
'use strict';
exports.execute = async function(context, params) {
    const aiFunctions = context.getAIFunctions();
    const result = await aiFunctions.invokeAgent(params.agent, {
        arguments: params.arguments,
        history: params.history
    });
    return result;
};

Step 2: Call from client-side code

const result = await context.executeAction('InvokeAIAgent', {
    agent: 'generate-code',
    arguments: {
        instructions: userPrompt,
        model: currentModel
    }
});

if (result.success) {
    processAIResult(result);
}

Using Pre-Built Agents

Code Generation

Generate JavaScript code for actions:

const aiFunctions = context.getAIFunctions();
const aiResult = await aiFunctions.invokeAgent('generate-code', {
    arguments: {
        instructions: 'Create a function to calculate order totals with tax',
        context: { model: 'Order' }
    }
});

Data Model Generation

Generate complete data models:

const aiFunctions = context.getAIFunctions();
const modelDef = await aiFunctions.invokeAgent('generate-data-model', {
    arguments: {
        instructions: 'Create a Customer model with contact information and order history'
    }
});

Query Generation

Create optimized database queries:

const aiFunctions = context.getAIFunctions();
const query = await aiFunctions.invokeAgent('generate-query', {
    arguments: {
        instructions: 'Find all orders from last month with status pending',
        model: 'Order'
    }
});

Content Processing

const aiFunctions = context.getAIFunctions();

// Clean HTML content
const cleaned = await aiFunctions.invokeAgent('clean-html', {
    arguments: { content: htmlString }
});

// Extract keywords
const keywords = await aiFunctions.invokeAgent('extract-keywords', {
    arguments: { text: documentContent }
});

// Translate content
const translated = await aiFunctions.invokeAgent('translate', {
    arguments: { text: content, targetLanguage: 'es' }
});

Media Processing

const aiFunctions = context.getAIFunctions();

// Transcribe audio to text
const transcript = await aiFunctions.invokeAgent('transcribe-audio', {
    arguments: { audioFile: fileChecksum }
});

// Extract text from images
const imageText = await aiFunctions.invokeAgent('transcribe-image', {
    arguments: { imageFile: imageChecksum }
});

AI Functions Framework

The AI Functions framework provides additional utility methods:

const aiFunctions = context.getAIFunctions();

// Detect language of text
const langInfo = aiFunctions.detectLanguage(text);
// Returns: { language: "English", code: "en" }

// Summarize documents
const summary = aiFunctions.summarizeDocument(document, {
    chunkSize: 4000,
    maxOutputTokens: 1000,
    temperature: 0.2,
    model: 'gemini-2.5-flash'
});

Building Custom AI Agents

Agent Architecture

Appivo's AI agent system is built on three core components:

ComponentDescription
AIAgentThe top-level container
AIChainThe execution flow with steps
AIStepIndividual processing units
AIAgent
└── AIChain
    ├── Input Parameters
    ├── Output Definition
    ├── Tools
    └── Steps (AIStep[])
        ├── Model Configuration
        ├── System Prompt
        ├── User Prompt
        ├── Retriever (optional)
        └── Links to next steps

Agent Configuration

AI agents are defined as JSON configurations:

{
  "name": "CustomerInsightsAgent",
  "description": "Analyzes customer feedback and generates actionable insights",
  "version": 1,

  "input": [
    {
      "name": "feedback",
      "type": "string",
      "description": "Customer feedback text to analyze"
    },
    {
      "name": "category",
      "type": "string",
      "description": "Feedback category (product/service/support)"
    },
    {
      "name": "context",
      "type": "object",
      "description": "Additional context data"
    }
  ],

  "output": {
    "type": "json",
    "example": {
      "sentiment": "positive|neutral|negative",
      "score": 0.85,
      "insights": ["insight1", "insight2"],
      "actionItems": ["action1", "action2"]
    }
  },

  "tools": [
    {
      "type": "java",
      "class": "com.appivo.services.aiservice.CodingTools"
    }
  ],

  "steps": [
    {
      "name": "AnalyzeStep",
      "maxCycles": 3,
      "chatWindowTokens": 32768,

      "model": {
        "provider": "google",
        "name": "gemini-2.5-pro",
        "temperature": 0.7,
        "maxOutputTokens": 4096
      },

      "systemPrompt": {
        "text": "You are an expert customer feedback analyst..."
      },

      "userPrompt": {
        "type": "template",
        "text": "Category: {{input.category}}\nFeedback: {{input.feedback}}\n\nAnalyze and provide insights."
      },

      "output": {
        "type": "json"
      }
    }
  ]
}

Model Configuration

"model": {
  "provider": "google|openai|anthropic",
  "name": "model-name",
  "temperature": 0.7,
  "maxOutputTokens": 4096,
  "topP": 0.95,
  "topK": 40
}

Available Models:

ProviderModels
Googlegemini-2.5-pro, gemini-2.5-flash, gemini-3-flash-preview
OpenAIgpt-4o, gpt-4o-mini, gpt-4-turbo
Anthropicclaude-3-haiku, claude-3-sonnet, claude-sonnet-4-20250514

Prompt Types

Simple Text Prompt:

"systemPrompt": {
  "text": "You are a helpful assistant."
}

Template Prompt (with Handlebars):

"userPrompt": {
  "type": "template",
  "text": "Process {{input.data}} for {{input.userName}}"
}

Multi-Part Prompt (with attachments):

"userPrompt": {
  "parts": [
    {
      "type": "text",
      "text": "Analyze this document:"
    },
    {
      "name": "document",
      "type": "document"
    },
    {
      "name": "image",
      "type": "image"
    }
  ]
}

Input/Output Types

Input Parameter Types:

  • string - Text input
  • number - Numeric value
  • boolean - True/false
  • object - Complex object
  • array - List of items

Output Types:

  • string - Plain text response
  • json - Structured JSON output
  • html - HTML formatted response

Multi-Step Agents

Create complex workflows by linking multiple steps:

{
  "name": "DocumentProcessor",
  "steps": [
    {
      "name": "ExtractInfo",
      "model": { "provider": "google", "name": "gemini-2.5-flash" },
      "output": { "type": "json" },
      "links": [
        {
          "condition": "output.documentType == 'invoice'",
          "nextStep": "ProcessInvoice"
        },
        {
          "condition": "output.documentType == 'receipt'",
          "nextStep": "ProcessReceipt"
        }
      ]
    },
    {
      "name": "ProcessInvoice",
      "model": { "provider": "google", "name": "gemini-2.5-pro" }
    },
    {
      "name": "ProcessReceipt",
      "model": { "provider": "google", "name": "gemini-2.5-flash" }
    }
  ]
}

Using Tools in Agents

Integrate tools for extended capabilities:

{
  "name": "DataAnalysisAgent",
  "tools": [
    {
      "type": "java",
      "class": "com.appivo.services.aiservice.CodingTools"
    }
  ],
  "steps": [
    {
      "name": "Analyze",
      "maxCycles": 5,
      "tools": ["getModels", "getModelDetails", "queryData"],
      "systemPrompt": {
        "text": "You have access to tools for data analysis. Use them to answer questions about the application's data."
      }
    }
  ]
}

Conversation Memory

Configure how agents maintain conversation context:

"steps": [
  {
    "name": "ConversationalStep",
    "chatWindowSize": 50,
    "chatWindowTokens": 32768,
    "includeFormat": true
  }
]

RAG with SearchIndexes

What Are SearchIndexes?

SearchIndexes enable Retrieval-Augmented Generation (RAG) by allowing AI agents to search through your application's documents and data to provide context-aware responses.

Creating a SearchIndex

  1. Go to Data → Search Indexes
  2. Create a new index
  3. Select the data model to index
  4. Choose attributes to include
  5. Configure search type

Search Types

TypeDescription
TEXTTraditional keyword search using BM25 algorithm
VECTORSemantic similarity search using embeddings
BOTHHybrid search combining both methods with Reciprocal Rank Fusion

Processing Options

OptionDescription
PreprocessorsClean or transform text before indexing
TransformersGenerate additional searchable content
ChunkingSplit large documents (2000 chars max, 200 char overlap by default)

Using SearchIndexes with Agents

Configure a retriever in your agent step:

{
  "name": "KnowledgeAgent",
  "steps": [
    {
      "name": "AnswerWithContext",
      "retriever": {
        "type": "searchIndex",
        "indexName": "KnowledgeBase",
        "maxResults": 5,
        "minScore": 0.7
      },
      "model": {
        "provider": "google",
        "name": "gemini-2.5-pro"
      },
      "systemPrompt": {
        "text": "Answer questions using the provided context. If the context doesn't contain the answer, say so."
      },
      "userPrompt": {
        "type": "template",
        "text": "Context:\n{{retrievedDocuments}}\n\nQuestion: {{input.question}}"
      }
    }
  ]
}

Searching from Actions

// Search for relevant documents
const searchResults = await context.searchIndex('CustomerDocsIndex', {
    query: 'refund policy',
    type: 'BOTH',
    limit: 5
});

// Use results with AI agent
const aiFunctions = context.getAIFunctions();
const response = await aiFunctions.invokeAgent('generate-response', {
    arguments: {
        question: userQuestion,
        context: searchResults.documents,
        instructions: 'Answer based on the provided context'
    }
});

Complete Agent Examples

Code Review Agent

{
  "name": "CodeReviewer",
  "description": "Reviews JavaScript code for Appivo best practices",
  "input": [
    { "name": "code", "type": "string" },
    { "name": "context", "type": "object" }
  ],
  "output": {
    "type": "json",
    "example": {
      "score": 85,
      "issues": [],
      "suggestions": []
    }
  },
  "tools": [
    {
      "type": "java",
      "class": "com.appivo.services.aiservice.CodingTools"
    }
  ],
  "steps": [
    {
      "name": "ReviewCode",
      "model": {
        "provider": "google",
        "name": "gemini-2.5-pro",
        "temperature": 0.3,
        "maxOutputTokens": 8000
      },
      "maxCycles": 3,
      "tools": ["getModelDetails", "getActions"],
      "systemPrompt": {
        "text": "You are an expert Appivo code reviewer. Analyze the code for security, performance, and best practices. You can use tools to understand the application context."
      },
      "userPrompt": {
        "type": "template",
        "text": "Review this code from {{input.context.action}}:\n\n```javascript\n{{input.code}}\n```"
      },
      "output": {
        "type": "json"
      }
    }
  ]
}

Multi-Language Translation Agent

{
  "name": "TranslationAgent",
  "input": [
    { "name": "text", "type": "string" },
    { "name": "sourceLang", "type": "string" },
    { "name": "targetLang", "type": "string" }
  ],
  "steps": [
    {
      "name": "DetectLanguage",
      "model": { "provider": "google", "name": "gemini-2.5-flash" },
      "output": { "type": "json" },
      "userPrompt": {
        "text": "Detect the language of: {{input.text}}"
      },
      "links": [
        {
          "condition": "output.confidence < 0.8",
          "nextStep": "ConfirmLanguage"
        },
        {
          "condition": "output.confidence >= 0.8",
          "nextStep": "Translate"
        }
      ]
    },
    {
      "name": "ConfirmLanguage",
      "model": { "provider": "google", "name": "gemini-2.5-pro" }
    },
    {
      "name": "Translate",
      "model": { "provider": "google", "name": "gemini-2.5-pro" },
      "systemPrompt": {
        "text": "You are a professional translator. Preserve formatting and tone."
      },
      "userPrompt": {
        "type": "template",
        "text": "Translate from {{input.sourceLang}} to {{input.targetLang}}:\n\n{{input.text}}"
      }
    }
  ]
}

Registering Custom Agents

  1. Go to the AI Agents section in the Application Builder
  2. Click Create New Agent
  3. Paste your JSON configuration
  4. Save the agent

Common Use Cases

Automated Code Generation

const model = 'Product';
const operations = ['create', 'read', 'update', 'delete'];

const aiFunctions = context.getAIFunctions();
for (const op of operations) {
    const code = await aiFunctions.invokeAgent('generate-code', {
        arguments: {
            instructions: `Generate ${op} operation for ${model}`,
            model: model,
            operation: op
        }
    });

    if (code.success) {
        await context.createRecord('Action', {
            name: `${model}_${op}`,
            script: code.result,
            type: 'SCRIPT'
        });
    }
}

Intelligent Data Validation

exports.execute = async function(context, params) {
    const aiFunctions = context.getAIFunctions();

    // Clean and validate HTML content
    const cleaned = await aiFunctions.invokeAgent('clean-html', {
        arguments: { content: params.userContent }
    });

    // Extract key information
    const extracted = await aiFunctions.invokeAgent('extract-keywords', {
        arguments: { text: cleaned.result }
    });

    return await context.createRecord('ProcessedContent', {
        original: params.userContent,
        cleaned: cleaned.result,
        keywords: extracted.result,
        processed_at: new Date()
    });
};

Smart Search and Responses

// Search relevant documents
const docs = await context.searchIndex('KnowledgeBase', {
    query: userQuestion,
    type: 'BOTH',
    limit: 10
});

// Generate contextual answer
const aiFunctions = context.getAIFunctions();
const answer = await aiFunctions.invokeAgent('generate-response', {
    arguments: {
        question: userQuestion,
        context: docs.documents.map(d => d.content).join('\n'),
        instructions: 'Provide a helpful answer based on the context'
    }
});

return {
    answer: answer.result,
    sources: docs.documents.map(d => d.title)
};

Automated Documentation

const actions = await context.query('Action', {
    filter: { type: 'SCRIPT' }
});

const aiFunctions = context.getAIFunctions();
for (const action of actions) {
    const docs = await aiFunctions.invokeAgent('generate-documentation', {
        arguments: {
            code: action.script,
            name: action.name,
            purpose: action.description
        }
    });

    if (docs.success) {
        await context.updateRecord('Action', action.id, {
            documentation: docs.result
        });
    }
}

Best Practices

Choose the Right Agent

TaskRecommended Agent
Creating action scriptsgenerate-code
Schema creationgenerate-data-model
Code reviewCode analyzers
Text/media processingContent processors

Provide Clear Context

// Good: Specific context
const aiFunctions = context.getAIFunctions();
const code = await aiFunctions.invokeAgent('generate-code', {
    arguments: {
        instructions: 'Create validation for email field',
        model: 'User',
        field: 'email',
        requirements: 'Must be unique and valid format'
    }
});

// Less effective: Vague instructions
const code = await aiFunctions.invokeAgent('generate-code', {
    arguments: {
        instructions: 'validate email'
    }
});

Handle Responses Properly

const aiFunctions = context.getAIFunctions();
try {
    const result = await aiFunctions.invokeAgent('agent-name', {
        arguments: params
    });

    if (result.success) {
        const data = result.result;
        if (data && data.code) {
            // Use generated code
        }
    } else {
        console.error('Agent failed:', result.error);
        // Provide fallback behavior
    }
} catch (error) {
    console.error('System error:', error);
}

Use Caching

For frequently requested AI operations:

const cacheKey = `ai_${agentName}_${JSON.stringify(params)}`;
let result = await context.getCache(cacheKey);

if (!result) {
    const aiFunctions = context.getAIFunctions();
    result = await aiFunctions.invokeAgent(agentName, {
        arguments: params
    });
    if (result.success) {
        await context.setCache(cacheKey, result, 3600); // Cache for 1 hour
    }
}

Troubleshooting

Agent Not Found

  • Verify agent name is correct
  • Check if agent is registered in your application
  • Ensure you have permissions to use the agent

Empty or Unexpected Results

  • Provide more specific instructions
  • Include relevant context and examples
  • Check agent configuration and prompts

Performance Issues

  • Use simpler models for basic tasks
  • Enable caching for repeated operations
  • Break complex tasks into steps

Token Limit Exceeded

  • Reduce input size
  • Use summarization before processing
  • Split large operations into chunks

API Reference

ContextMethodDescription
Server-sidecontext.getAIFunctions().invokeAgent()Invoke any AI agent
Server-sideaiFunctions.detectLanguage()Detect text language
Server-sideaiFunctions.summarizeDocument()Summarize documents
Client-side<aibutton agent="name">AI button widget

Next Steps