Dynamic AI Service

The Dynamic AI Service is the engine that powers AI classification, intent matching, and query generation across Nviti.ng. It communicates with AI providers (like Google Gemini) using the OpenAI-compatible API format and returns structured responses.

Overview

DynamicAIService handles:

  • Intent classification — Matching user messages to pattern groups
  • Custom prompt handling — Running arbitrary AI prompts with structured output
  • Table query validation — Validating SQL queries and translating them to MongoDB
  • Table query generation — Generating SQL from natural language descriptions
  • Usage logging — Tracking token usage, costs, and credits for every AI call

How It Works

The service is initialized with a model type (default: nviti-ai-1.0-match), an optional company, and an optional custom agent. It resolves the underlying Agent model (which stores API keys, base URLs, and cost configurations) and uses it for all subsequent API calls.

All requests use the OpenAI-compatible tools/function_calling pattern to get structured JSON responses from the AI model.

Methods

handle(string $message, array $classificationContext, array $expectedStructure, ...): ?array

The main entry point for classification and intent matching. Sends a user message with classification context and expects a structured response matching the provided JSON schema.

Parameters:

  • message (string) — The user's message to classify
  • classificationContext (array) — Pattern groups and matching context
  • expectedStructure (array) — JSON schema for the expected response

Returns: Array with success, data, usage, and raw_response keys, or null if no agent is available.

handleWithCustomPrompt(string $userMessage, string $systemPrompt, array $expectedStructure, ...): ?array

Like handle() but with a custom system prompt instead of the default intent classifier prompt.

Parameters:

  • userMessage (string) — The raw user message
  • systemPrompt (string) — Custom system instructions
  • expectedStructure (array) — JSON schema for the expected response

Returns: Same structure as handle().

validateTableQuery(string $sql, DynamicTable $table, ...): ?array

Validates a SQL query for safety (SELECT only, no destructive operations) and translates it into an equivalent MongoDB query. Used by the Table Tool system.

Parameters:

  • sql (string) — The SQL query to validate
  • table (DynamicTable) — The target dynamic table (used for schema context)
  • companyId (int, optional) — Company ID for usage logging
  • tenantId (string, optional) — Tenant ID for usage logging
  • queryDescription (string, optional) — Natural language description of the query
  • currentMongoQuery (mixed, optional) — Current MongoDB query for iterative refinement
  • executionError (mixed, optional) — Previous execution error for retry context

Returns: Array with success, data (containing valid, sql, mongodb_query, reason), or null.

generateTableQuery(string $description, DynamicTable $table, ...): ?array

Generates a SQL SELECT query from a natural language description. Used when the user writes a description instead of manual SQL.

Parameters:

  • description (string) — What the query should do, in plain English
  • table (DynamicTable) — The target dynamic table

Returns: Array with success, data (containing sql and explanation), or null.

Credit System

Each AI request checks the tenant's available credits before proceeding. If credits are below the threshold (default 0.5), the request is rejected. Some tenants are exempt from charging via skipChargeForTenant().

Usage Logging

Every API call creates an AIUsageLog record tracking:

  • Token counts (input, output, total)
  • Costs (input, output, total)
  • Credits used
  • Model name, type, company, tenant
  • Execution time
  • Success/failure status

Constants

Constant Value Purpose
TYPE_CLASSIFICATION 'classification' General classification requests
TYPE_INTENT_MATCH 'intent_match' Intent matching requests

See Also

  • Agent Tools — The tools that use this service for table queries
  • AI Assistants — Configure the AI agents this service communicates with
  • Test file: tests/Feature/Services/DynamicAIServiceTest.php

Keywords

AI service, dynamic AI, classification, intent matching, query validation, SQL validation, MongoDB translation, structured response, function calling, usage logging, token tracking