Complete Chat Example

A complete chat example that integrates with NeuralAI APIs. Supports chat, image generation, music, video, and web search with automatic intent detection.

✨ Features

  • Automatic intent detection (chat, image, video, music, seek, code)
  • Multiple file upload (images, PDF, documents)
  • Advanced markdown rendering (tables, Mermaid diagrams, formatted JSON)
  • Download generated media (images/audio/video)
  • Clarification handling (follow-up questions)
  • Responsive and modern UI
  • Voice input - Automatic transcription from microphone (Web Speech API)
  • Audio playback - Google neural voices (Neural2) for text responses + audio/music playback
  • 🧠Knowledge Base integration - Checkbox to automatically search your KB documents associated with the API key
  • 🧠Conversation memory - two histories you can enable/disable from the new tabs: ☁️ Storage (server-side session memory, session_id) and 💾 Local Storage (last 10 messages in localStorage as conversation_history, +1 flat token)
  • 📄Professional PDF export - 📄 PDF button on every AI answer: generates an A4 document with cover, tables and sources (generate_pdf: true, 5 tokens)
  • 📊Google Slides export - 📊 Google Slides button under every AI-generated PDF presentation: recreates the deck as an EDITABLE presentation in your Google account (10 tokens; requires NeuralAI login in the same browser and a connected Google Slides connector)

🧠 MEMORY AND PDF EXPORT IN THIS EXAMPLE

  • The local history (last 10 messages) is enabled from the 💾 Local Storage tab: it is saved in localStorage under neuralai_chat_history and sent as conversation_history with every request — follow-ups work without repeating the context.
  • The 🗑 Reset memory button in the header immediately clears the local history and resets the server session on the next request (reset: true): the response contains a fresh clean session_id.
  • Cost: +1 flat token per request with active memory. The first request without memory pays no surcharge.
  • The 📄 PDF button on every answer sends the text with generate_pdf: true and opens result.pdf_url in a new tab — professional A4 PDF (5 tokens).

☁️💾 Storage and Local Storage History (new tabs)

The chat example has two new tabs, each with an info card explaining what happens to storage when you enable it and a switch to turn it on/off. They are independent: you can keep both enabled, just one, or none. When a history is enabled, the dot on its tab turns green.

☁️ Storage tab — server history (session_id)

When enabled, every request sends the session_id: the API saves the session on the NeuralAI database (rolling window of 20 messages, automatic deletion after 30 days of inactivity) and the new session_id returned in the response is saved in localStorage under neuralai_session_id.

💾 Local Storage tab — browser history (conversation_history)

When enabled, the last 10 messages are saved in the browser localStorage (key neuralai_chat_history) and sent with every request as conversation_history: no data is stored on the server, maximum privacy.

🗑 Reset memory — server session reset

The header button immediately deletes the local history and marks a pending reset: the next request sends reset: true with the session_id, the API deletes the session from the database and returns a clean session_id — the reset costs no extra tokens.

🧠 Dynamic — orchestrator dynamic behavior

The 🧠 Dynamic button in the header enables/disables dynamic_mode: on every request the orchestrator analyzes the user's mood, technical level and preferred format and adapts the tone and structure of the answer (Flash model, +5 tokens per active request). The state is persisted in localStorage (key neuralai_dynamic_mode) and stays active after reopening the page; the detected profile is returned in result.dynamic.

New functions added to chat.js:

toggleStorageHistory()toggleLocalStorageHistory()toggleDynamicMode()toggleStoragePanel()toggleLocalStoragePanel()resetConversationMemory()renderHistoryUI()applyHistoryI18n()
let requestBody = { api_key: API_KEY, prompt: finalPrompt, ... };

// Tab ☁️ Storage: cronologia server (session_id + reset pendente)
if (storageHistoryEnabled) {
  if (sessionId) requestBody.session_id = sessionId;
  if (pendingSessionReset) { requestBody.reset = true; pendingSessionReset = false; }
}

// Tab 💾 Local Storage: cronologia browser (ultimi 10 messaggi)
if (localStorageHistoryEnabled && conversationHistory.length > 0) {
  requestBody.conversation_history = conversationHistory.slice(-10);
}

The state of the two switches is persisted in localStorage (keys neuralai_storage_history and neuralai_local_history) and stays active even after reopening the page. Both histories can be enabled together: in that case the request sends both session_id and conversation_history. Cost: +1 flat token per request with active memory.

1. index.html - Chat Interface

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

2. chat.js - JavaScript Logic

javascript
// chat.js - Full NeuralAI Chat with RAG Documents, RAG Video, TTS, Microphone
const API_URL = 'https://app.neuralaiweb.com/functions/neuralaiPublicApi';
const UPLOAD_URL = 'https://app.neuralaiweb.com/functions/publicUploadFile';
const EXTRACT_URL = 'https://app.neuralaiweb.com/functions/extractDocumentText';
const API_KEY = 'YOUR_API_KEY_HERE';

📦 How to use

Contains index.html and chat.js ready to use - extract and use immediately

⚡ Alternative: copy the code blocks above and create files manually

  1. Extract the ZIP or create a folder (e.g. chat-neuralai/)
  2. In chat.js, replace LA_TUA_CHIAVE_API_QUI with your key from /api-hub/keys
  3. Open index.html in the browser
  4. If you have a Knowledge Base, check the 🧠 KB in the header to search your documents
  5. Open the ☁️ Storage or 💾 Local Storage tab and enable the history you want with the switch
  6. Write a message or click the microphone 🎤 to speak
  7. Ask follow-ups like 'and next week?' — memory is automatic; use 🗑 Reset memory to start over
  8. Click 📄 PDF on an answer to export it as a professional A4 PDF (5 tokens)

📊 Structured Data Visualization - Instructions

AI will automatically return formatted data when appropriate. Here's how to request each format:

📋 Markdown Tables

Ask AI to create comparative tables or structured data:

"Create a comparative table of features between iPhone 15 and Samsung S24"

🔄 Mermaid Diagrams

Request flowcharts, sequence diagrams, or charts:

"Create a flowchart showing the user authentication process"

💡 Supported types: flowchart, sequenceDiagram, gantt, classDiagram, stateDiagram, erDiagram

📝 JSON and Structured Data

Request output in JSON format for structured data:

"Return user data in JSON format"

💡 Supported formats: json, data, yaml, yml - with automatic syntax highlighting

💻 Code Blocks

For code snippets, AI will automatically use code blocks:

"Write a Python function to calculate factorial"

✨ All formats are automatically rendered in the chat - no additional configuration needed!

🧠 Knowledge Base Integration:

The chat supports automatic search in your Knowledge Base documents:

  • Check the 🧠 KB to enable KB search
  • You must have created a KB from the NeuralAI dashboard and associated it with your API key
  • The API will automatically search in all KBs associated with your API key

⚠️ Important Notes

  • The API key must be inserted in chat.js - don't share it publicly
  • For production, use a backend proxy to hide the key
  • Media URLs expire after 1 hour - download them for permanent use
  • Supports up to 3 attached files per request
  • Voice input requires a compatible browser (Chrome, Edge, Safari)
  • Audio content is automatically played with HTML5 player
  • Each request with active memory costs +1 flat token; each PDF export costs 5 tokens (no orchestrator cost)