Frontend Integration Guidev1.0

Nuvion IQ

AI-powered conversational interface enabling users to perform actions through natural language conversations.

AI-Powered

GPT-4 driven

Conversational

Natural language

Smart Context

Auto-detects intent

Action Ready

Generates payloads

01

Overview

Nuvion IQ is an AI-powered conversational interface that allows users to perform actions through natural language conversations. Users can create accounts and send money by chatting with an AI assistant that collects required information conversationally and executes API calls on their behalf.

Create AccountsSend MoneyBank TransfersMobile Money
02

Architecture

How It Works

User UI

Frontend

IQ Session

Endpoints

LLM

AI Service

Backend

API

Data flows back through the same path

Flow Diagram

Step 1: Creates or updates IQ session

03

Authentication

All IQ endpoints require authentication via JWT token

Authorization: Bearer <jwt_token>

The token provides:

entity_id

User's organization/business ID

user_id

User's identity ID

identity

Full user identity object

entity

Full entity object

These are automatically populated by the backend.

04

Available Endpoints

POST/iq-sessions

Creates a new conversational session or continues an existing one

Request Fields

FieldTypeRequiredDescription
session_referencestringYesUnique session identifier. Format: {entity_id}_{timestamp}
messagestringYesUser's initial message (max 240 chars)
context_codestringNoContext hint: create-account or send-money

Request Body

{
  "session_reference": "01JEF8XYZ123456789ABCDEF_1733750400000",
  "message": "I want to send money to John",
  "context_code": "send-money"
}

Response (201 Created)

{
  "status": 200,
  "message": "IQ session created successfully",
  "data": {
    "id": "01JEF8XYZ123456789ABCDEF",
    "session_reference": "01JEF8XYZ123456789ABCDEF_1733750400000",
    "messages": [
      {
        "sender": "user",
        "text": "I want to send money to John",
        "created": 1733750400000
      },
      {
        "sender": "system",
        "text": "I'd be happy to help you send money!...",
        "created": 1733750401234
      }
    ],
    "status": "active",
    "context": {
      "data": {
        "context_code": "send-money",
        "endpoint": "/bank-transfers",
        "method": "POST"
      }
    }
  }
}
05

Session Status States

"active"

Ready for next user message

Frontend Action: Allow user to type/send messages

"processing"

AI is thinking/responding

Frontend Action: Show loading indicator, disable input

"ready"

Payload ready for API call

Frontend Action: Extract payload, call target API

"closed"

Session ended by user

Frontend Action: Show session ended message

Status: "ready" - Executing Actions

When the AI collects all required information, the session status changes to "ready" and context.data includes the full payload:

Ready Payload Structure

{
  "status": "ready",
  "context": {
    "data": {
      "context_code": "send-money",
      "endpoint": "/bank-transfers",
      "method": "POST",
      "payload": {
        "amount": 500,
        "currency": "USD",
        "narration": "Payment to John",
        "account_id": "01JEF8XYZ123456789ABCDEF",
        "counterparty_id": "01JEF8ABC123456789DEFGHI",
        "unique_reference": "TXN_1733750500000"
      },
      "ready": true
    }
  }
}

Frontend Implementation

// Check if session is ready
if (session.status === 'ready' && session.context.data.ready) {
  const { endpoint, method, payload } = session.context.data;
  
  // Call the target API
  const response = await fetch(`https://api.nuvion.com${endpoint}`, {
    method: method,
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(payload)
  });
  
  const result = await response.json();
  
  // Optionally, send the result back to IQ
  if (result.status === 'success') {
    await sendMessage({
      session_reference: session.session_reference,
      message: `API_RESULT: ${JSON.stringify(result)}`
    });
  }
}
06

Available Contexts

Purpose: Help users create a new account (debit, checking, operational, or safeguard) for their entity

Target Endpoint: POST /accounts

Required Fields

  • entity_id

    Entity ID (26 char ULID) - auto-populated from session

  • type

    Account type: debit, checking, operational, or safeguard

  • currency

    3-letter currency code (USD, EUR, GHS, NGN, KES, UGX, TZS, ZAR, GBP)

  • display_name

    User-friendly account name (1-255 chars, must be unique)

Optional Fields

  • meta

    Additional metadata (custom key-value pairs)

  • config.is_overdraftable

    Allow negative balance (boolean)

  • config.overdraft_limit

    Maximum overdraft amount (positive number)

07

Best Practices

Follow these patterns for robust frontend implementation of Nuvion IQ.

1. Session Reference Generation

function generateSessionReference(entityId) {
  const timestamp = Date.now();
  return `${entityId}_${timestamp}`;
}

// Usage
const sessionRef = generateSessionReference(user.entity_id);

2. Message Character Limit

const MAX_MESSAGE_LENGTH = 240;

function validateMessage(message) {
  if (message.length > MAX_MESSAGE_LENGTH) {
    throw new Error(`Message too long. Maximum ${MAX_MESSAGE_LENGTH} characters.`);
  }
  return message.trim();
}

3. Session State Management

const IQSession = {
  current: null,
  
  async start(message, contextCode) {
    const response = await createSession({
      session_reference: generateSessionReference(user.entity_id),
      message,
      context_code: contextCode
    });
    this.current = response.data;
    return this.current;
  },
  
  async sendMessage(message) {
    if (!this.current) throw new Error('No active session');
    
    const response = await sendMessage({
      session_reference: this.current.session_reference,
      message
    });
    this.current = response.data;
    return this.current;
  },
  
  async refresh() {
    if (!this.current) throw new Error('No active session');
    
    const response = await getSession(this.current.session_reference);
    this.current = response.data;
    return this.current;
  },
  
  isReady() {
    return this.current?.status === 'ready' && 
           this.current?.context?.data?.ready === true;
  },
  
  isProcessing() {
    return this.current?.status === 'processing';
  },
  
  getPayload() {
    if (!this.isReady()) return null;
    return this.current.context.data;
  }
};

4. Handling "Processing" State

async function sendMessageWithPolling(message) {
  // Send message
  let session = await IQSession.sendMessage(message);
  
  // If still processing, poll for completion
  if (session.status === 'processing') {
    await new Promise(resolve => setTimeout(resolve, 1000));
    session = await IQSession.refresh();
  }
  
  return session;
}

5. Executing Ready Actions

async function executeReadyAction() {
  if (!IQSession.isReady()) return;
  
  const { endpoint, method, payload } = IQSession.getPayload();
  
  try {
    const response = await apiClient.request({
      method,
      url: endpoint,
      data: payload
    });
    
    // Optionally inform the AI of success
    await IQSession.sendMessage(
      `Great! The ${IQSession.current.context.data.context_code} action completed successfully.`
    );
    
    return response.data;
  } catch (error) {
    // Optionally inform the AI of failure
    await IQSession.sendMessage(
      `There was an issue: ${error.message}. Can we try again?`
    );
    throw error;
  }
}
08

Error Handling

Always implement proper error handling to provide a smooth user experience.

Session Not Found

404|NOTFOUND
{
  "status": "error",
  "message": "IQ session not found",
  "code": "NOTFOUND"
}

Cause

Invalid session_reference or session belongs to another user

Action

Create a new session

Session Processing

400|INVLDREQ
{
  "status": "error",
  "message": "Session is currently processing. Please wait.",
  "code": "INVLDREQ"
}

Cause

Sent a message while AI is still responding

Action

Wait 1-2 seconds and try again, or poll session status

Message Limit Reached

429|LIMITERR
{
  "status": "error",
  "message": "Message limit reached for this session (1000 max)",
  "code": "LIMITERR"
}

Cause

Session has 1000 messages already

Action

Create a new session

Message Too Long

400|VALIDATIONERR
{
  "status": "error",
  "message": "Message exceeds maximum length of 240 characters",
  "code": "VALIDATIONERR"
}

Cause

Message > 240 characters

Action

Validate message length before sending

09

UI/UX Recommendations

Nuvion IQ - AI Assistant
I want to send money to John
I'd be happy to help you send money! How much would you like to send and in what currency?
500 USD
Great! 500 USD. Who is the recipient?...

Status Indicators

Active

Green dot, "Ready for input"

Processing

Animated dots, "AI is thinking..."

Ready

Action button, "Execute Transfer"

Closed

Gray, "Session ended"

Suggested Features

Context Shortcuts

Quick buttons for "Send Money" or "Create Account"

Message History

Persist and display past sessions

Copy Payload

Allow users to review generated payload before executing

Undo/Edit

Let users correct information before finalizing

Voice Input

Support voice-to-text for easier interaction

Rich Responses

Format currency, dates, and IDs nicely

10

Testing Checklist

0 of 12 completed

0%

Environment Variables

Backend requires:

# OpenAI API Configuration
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4  # or gpt-3.5-turbo

# IQ Context Source
IQ_CONTEXT_SOURCE=file  # or 'database' for future DB support
11

API Reference

Complete API Reference

EndpointMethodPathAuthBodyResponse
Create SessionPOST/iq-sessionsRequired (JWT){ session_reference, message, context_code? }Session object with messages
Get SessionGET/iq-sessions/:session_referenceRequired (JWT)Session object with messages
Send MessagePOST/iq-session-messagesRequired (JWT){ session_reference, message }Updated session object with messages

Support & Questions

  • Endpoints: Check this document or contact backend team
  • AI Behavior: Review context definitions in /contexts/iq-contexts.json
  • Integration Issues: Provide session_reference and error details