🧠Complete KB Chat Example

Complete chat with Knowledge Base, optional web search, media generation (images/video/music/code) and voice interaction.

Knowledge Base Integration

RAG with documents and web sources

Intent Detection

Automatic detection chat/image/video/music/code

Web Speech API

Free voice input + TTS Google Neural2

Conversation Memory

Persistent conversation_history in localStorage (last 10 messages) with reset button

PDF Export

📄 PDF button on every answer (generate_pdf: true, 5 tokens)

Main JavaScript Functions

The kb-chat.js code includes 16 main functions that handle all aspects of the chat with Knowledge Base.

Esempi di Utilizzo Reali

// Rileva intento da prompt

const intent = detectIntent("Crea un'immagine di un tramonto");

// Restituisce: "image"

// Converti markdown con diagrammi

const html = markdownToHtml("## Titolo\\n\\n- Lista\\n- Item");

// Restituisce HTML con rendering Mermaid

// Aggiungi messaggio con immagine

appendMessageWithImage(messagesEl, "assistant", imageUrl, "image");

🎯 Core Functions

detectIntent()

Analyzes the prompt and detects intent (chat, image, video, music, code)

detectBrowserLanguage()

Automatically detects browser language

markdownToHtml()

Converts markdown to HTML with Mermaid support for diagrams

💬 UI Functions

appendMessage()

Adds text messages to the chat

appendMessageWithImage()

Renders AI-generated images

appendMessageWithVideo()

Displays generated videos

appendMessageWithAudio()

Plays TTS audio (text-to-speech)

appendMessageWithCode()

Shows code with syntax highlighting

⚡ Advanced Functions

initMicrophone()

Initializes voice input with Web Speech API

stripForTTS()

Cleans text for speech synthesis

resetSpeakBtn()

Manages microphone button state

🧠 Conversation Memory and PDF Export

getConversationHistory()

Loads history from localStorage (last 10 messages)

saveToConversationHistory()

Saves each user/assistant message to localStorage

resetConversationMemory()

Clears the local history (🗑 button in the header)

exportMessageAsPdf()

Sends the answer with generate_pdf: true and opens result.pdf_url in a new tab (5 tokens)

exportDeckToGoogleSlides()

Exports the deck (result.deck) of a PDF presentation as an EDITABLE Google Slides presentation in your Google account (10 tokens; requires NeuralAI login and a connected Google Slides connector)

The history persists in localStorage under neuralai_chat_history and is sent as conversation_history with every request: follow-ups work without repeating the context (+1 flat token per request with active memory). The 📄 PDF button generates a professional A4 document from every answer (generate_pdf: true, 5 tokens).

Complete Request Flow

1

User Input

User types or speaks

2

Detect Intent

detectIntent()

3

Call API

neuralaiPublicApi

4

Process Response

markdownToHtml()

5

Render

appendMessage*()

API Key Configuration

The API key can be configured in two ways:

1. Via LocalStorage (recommended for testing)

localStorage.setItem('neuralai_api_key', 'nai_xxxxx');

2. Via Header Authorization

Authorization: Bearer nai_xxxxx

⚠️ For production, always use a backend proxy to hide the API key.

kb-chat.html

HTML structure of the Knowledge Base chat, including CSS styles for the responsive interface and support for Mermaid diagrams.

html
<!DOCTYPE html>
<html lang="it">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

kb-chat.js

JavaScript logic for the chat: intent detection, API call, markdown rendering, TTS, and microphone support.

javascript
// kb-chat.js - Knowledge Base Chat with multi-intent support
// Config, intent detection, markdown parsing, and message rendering utilities
const API_KEY = "YOUR_API_KEY_HERE";
const KB_URL = "https://app.neuralaiweb.com/functions/neuralaiPublicApi";
const KB_ID = ""; // Opzionale: inserisci l'ID della tua Knowledge Base. Se vuoto, usa tutte le KB associate alla API key.

app.js

JavaScript logic (part 2): media rendering (video/audio/code), chat initialization, voice input and API handling.

javascript
// app.js - Knowledge Base Chat (Part 2) - Video/audio/code rendering and main chat logic
function appendMessageWithVideo(messagesEl, role, src, intent) {
  const el = appendMessage(messagesEl, role, '', intent);
  const video = document.createElement('video');
  video.src = src; video.controls = true; video.className = 'msg-media'; video.style.cssText = 'max-width: 100%; border-radius: 8px; margin: 8px 0;';

💡 Production Tips

🔒 API Key Security

Never expose the API key in the frontend. Use a backend proxy with authentication for API calls in production.

⚡ Rate Limiting

Implement a rate limiting system to prevent abuse (10 requests/minute per user is a good starting point).

💾 Error Handling

Add retry logic with exponential backoff to handle API timeouts and temporary failures.

📊 Monitoring

Track token consumption, response times and errors to optimize costs and performance.

📚 Next steps: Consult the complete API documentation for advanced integration examples, webhooks for real-time updates, and best practices to scale your application.