Costruisci un chatbot AI alimentato da ChatGPT per WhatsApp per la tua azienda

2 novembre 2023

Esegui in pochi minuti un chatbot AI personalizzabile e specifico per la tua attività, completamente funzionale su WhatsApp. Ora supporta GPT-4o (multimodale) e caricamento dati esterni migliorato e chiamate API remote (RAG)

Trasforma il tuo numero WhatsApp in un potente chatbot AI alimentato da ChatGPT in pochi minuti con questo tutorial, usando Node.js, ChatGPT (modello GPT-4o) e Wassenger API.

Seguendo questo tutorial sarai in grado di avere un chatbot AI completamente funzionale simile a ChatGPT in esecuzione in pochi minuti sul tuo computer o server cloud che si comporta come un assistente virtuale di supporto clienti per uno specifico scopo aziendale.

Puoi facilmente personalizzare e istruire il bot AI per regolare il suo comportamento, ruolo, scopo e limiti di conoscenza. Inoltre, il bot AI sarà consapevole della conversazione basandosi sulla cronologia dei messaggi precedenti con l'utente su WhatsApp, permettendo risposte più accurate e contestualizzate.

Il chatbot può comprendere e rispondere in molte lingue ed è stato addestrato a comportarsi come un assistente virtuale di supporto clienti per scopi aziendali.

Inoltre, puoi facilmente aumentare la conoscenza specifica del dominio della tua azienda in tempo reale utilizzando azioni di funzione che consentono al bot AI di comunicare arbitrariamente con le funzioni del tuo codice o API remote per recuperare e fornire informazioni personalizzate al modello. Trova un esempio qui.

Il codice per questo tutorial è disponibile su GitHub💻

Puoi anche eseguire il programma del bot direttamente dal tuo browser senza installare alcun software o codice cliccando quie 🎉

🤩 🤖 Wassenger è una soluzione completa per le API di WhatsApp. Iscriviti per una prova gratuita di 7 giorni e inizia in pochi minuti!

Conversazione demo su WhatsApp alimentata dal chatbot ChatGPT utilizzando questo tutorial

Contenuti

🤑 💰 Guadagna il 30% di commissione riferendo utenti a Wassenger. Ottieni il tuo link di referral ora. Si applicano termini.

Come funziona

1. Avvia un servizio web che si connette automaticamente all'API di Wassenger e al tuo numero WhatsApp

2. Crea un tunnel usando Ngrok per poter ricevere eventi Webhook sul tuo computer (oppure puoi usare un URL webhook dedicato se esegui il programma del bot sul tuo server cloud).

3. Registra automaticamente l'endpoint webhook per ricevere i messaggi in arrivo.

4. Elabora e risponde ai messaggi ricevuti utilizzando un modello AI alimentato da ChatGPT addestrato con istruzioni personalizzate.

5. Puoi iniziare a provare il bot AI inviando messaggi al numero WhatsApp connesso a Wassenger.

Funzionalità

Questo tutorial fornisce un'implementazione completa di un chatbot AI alimentato da ChatGPT in Node.js che:

  • Fornisce un chatbot completo sul tuo numero WhatsApp connesso a Wassenger
  • Risponde automaticamente a qualsiasi messaggio in arrivo da utenti arbitrari
  • Può comprendere qualsiasi testo in linguaggio naturale e rispondere in oltre 90 lingue umane
  • Permette a qualsiasi utente di chiedere di parlare con un umano, nel qual caso la chat verrà assegnata a un agente ed uscirà dal flusso del bot
  • Il comportamento del bot AI può essere facilmente regolato nel file di configurazione (apri config.js)

Comportamento del bot

Il bot AI risponderà sempre ai messaggi in arrivo basandosi sui seguenti criteri:

  • La chat appartiene a un utente (le chat di gruppo sono sempre ignorate)
  • La chat non è assegnata a nessun agente all'interno di Wassenger
  • La chat non ha nessuna delle etichette bloccate (vedi config.js)
  • Il numero dell'utente della chat non è stato messo in blacklist (vedi config.js)
  • La chat o il contatto non sono archiviati o bloccati
  • Se una chat viene deassegnata da un agente, il bot la prenderà nuovamente in carico e risponderà automaticamente ai nuovi messaggi in arrivo

Requisiti

Struttura del progetto

Esplora i file sorgente su GitHub

\
|- bot.js -> the bot source code in a single file
|- config.js -> configuration file to customize credentials and bot behavior
|- actions.js -> functions to perform actions through the Wassenger API
|- server.js -> initializes the web server to process webhook events
|- main.js -> initializes the bot server and creates the webhook tunnel (when applicable)
|- store.js -> the bot source code in a single file
|- package.json -> node.js package manifest required to install dependencies
|- node_modules -> where the project dependencies will be installed, managed by npm

Installazione

Se hai git installato, esegui il seguente comando dal Terminale:

git clone https://github.com/wassengerhq/whatsapp-chatgpt-bot.git

Se non hai `git`, scarica i file sorgente del progetto qui e decomprimili.

Ecco come appare la chat web cooperativa ottimizzata dal team di Wassenger. Iscriviti gratuitamente

🤑 💰 Guadagna il 30% di commissione riferendo utenti a Wassenger. Ottieni il tuo link di referral ora. Si applicano termini.

Configurazione

Apri il tuo terminale preferito e cambia directory nella cartella del progetto dove si trova `package.json`:

cd whatsapp-chatgpt-bot/

Da quella cartella, installa le dipendenze eseguendo:

npm install

Con il tuo editor preferito, apri il file `config.js` e segui i passaggi seguenti.

Imposta la tua API key di Wassenger

Inserisci la tua API key di Wassenger

Puoi iscriverti gratuitamente qui e poi ottenere la API key qui:

// Required. Specify the Wassenger API key to be used // You can obtain it here: https://app.wassenger.com/apikeys apiKey: env.API_KEY || 'ENTER API KEY HERE',

Imposta la tua API key di OpenAI

Inserisci la tua API key di OpenAI

Iscriviti gratuitamente a OpenAI e poi ottieni la API key qui:

// Required. Specify the OpenAI API key to be used // You can sign up for free here: https://platform.openai.com/signup // Obtain your API key here: https://platform.openai.com/account/api-keys openaiKey: env.OPENAI_API_KEY || 'ENTER OPENAI API KEY HERE',

Imposta il tuo token Ngrok (opzionale)

Se hai bisogno di eseguire il programma sul tuo computer locale, il programma deve creare un tunnel usando Ngrok per processare gli eventi webhook dei messaggi WhatsApp in arrivo.

Iscriviti a Ngrok per un account gratuito e poi ottieni il tuo token di autenticazione come spiegato qui.

Imposta il token in `config.js` alla linea 90:

// Ngrok tunnel authentication token. // Required if webhook URL is not provided. // sign up for free and get one: https://ngrok.com/signup // Learn how to obtain the auth token: https://ngrok.com/docs/agent/#authtokens ngrokToken: env.NGROK_TOKEN || 'ENTER NGROK TOKEN HERE',

Se esegui il programma su un server cloud pubblico accessibile da Internet, non è necessario usare Ngrok. Invece, imposta l'URL del tuo server nel campo `webhookUrl` di `config.js`.

Personalizzazione

Puoi personalizzare il comportamento del chatbot definendo un insieme di istruzioni in linguaggio naturale che l'AI seguirà.

Leggi i commenti nel codice per ulteriori istruzioni.

Inoltre, puoi facilmente adattare il codice per soddisfare requisiti più specifici. Le possibilità sono quasi infinite!

Per procedere con la personalizzazione, apri config.js con il tuo editor e imposta le istruzioni del bot, il messaggio di benvenuto e il messaggio predefinito in base alle tue preferenze:

// Default message when the user sends an unknown message. const unknownCommandMessage = `I'm sorry, I can only understand text. Can you please describe your query? If you would like to chat with a human, just reply with *human*.`

// Default welcome message. Change it as you need. const welcomeMessage = `Hey there 👋 Welcome to this ChatGPT-powered AI chatbot demo using *Wassenger API*! I can also speak many languages 😁`

// AI bot instructions to adjust its behaviour. Change it as you need. // Use concise and clear instructions. const botInstructions = `You are a smart virtual customer support assistant that works for Wassenger. You can identify yourself as Molly, the Wassenger chatbot assistant. You will be chatting with random customers who may contact you with general queries about the product. Wassenger is a cloud solution that offers WhatsApp API and multi-user live communication services designed for businesses and developers. Wassenger also enables customers to automate WhatsApp communication and build chatbots. You are an expert in customer support. Be polite, be gentle, be helpful and emphatic. Politely reject any queries that are not related to customer support or Wassenger itself. Strictly stick to your role as a customer support virtual assistant for Wassenger. If you can't help with something, ask the user to type *human* in order to talk with customer support.`

// Default help message. Change it as you need. const defaultMessage = `Don't be shy 😁 try asking anything to the AI chatbot, using natural language! Example queries: 1️⃣ Explain me what is Wassenger 2️⃣ Can I use Wassenger to send automatic messages? 3️⃣ Can I schedule messages using Wassenger? 4️⃣ Is there a free trial available? Type *human* to talk with a person. The chat will be assigned to an available member of the team. Give it a try! 😁`

Apri il file di configurazione completo con tutte le opzioni disponibili

Chiamare dati esterni e API (RAG)

Con le chiamate di funzione, puoi facilmente fornire al modello AI informazioni contestuali, in tempo reale e specifiche dell'utente per generare risposte migliori e più accurate utilizzando tecniche di Retrieval-Augmented Generation (RAG).

Dietro le quinte, utilizza la funzionalità OpenAI Tool Function Calling.

Quando il modello AI ha bisogno di determinate informazioni, istruirà l'esecuzione di una o più funzioni per recuperare informazioni aggiuntive; ad esempio, in una funzione puoi interrogare un'API CRM esterna o un database per recuperare informazioni specifiche del cliente con cui l'agente AI sta chattando, come indirizzo email, nome utente, indirizzo di spedizione, ecc., quindi fornire tali informazioni come testo o JSON al modello AI per generare risposte accurate e specifiche per l'utente.

L'uso di funzioni strumento è potente e ti permette di costruire casi d'uso complessi e specifici per dominio per un agente AI.

Ecco un esempio di implementazione RAG con più funzioni strumento:

// Tool functions to be consumed by the AI when needed. // Edit as needed to cover your business use cases. // Using it you can instruct the AI to inform you to execute arbitrary functions // in your code based in order to augment information for a specific user query. // For example, you can call an external CRM in order to retrieve, save or validate // specific information about the customer, such as email, phone number, user ID, etc. // Learn more here: https://platform.openai.com/docs/guides/function-calling const functions = [ // Sample function to retrieve plan prices of the product // Edit as needed to cover your business use cases { name: 'getPlanPrices', description: 'Get available plans and prices information available in Wassenger', parameters: { type: 'object', properties: {} }, // Function implementation that will be executed when the AI requires to call this function // The function must return a string with the information to be sent back to the AI for the response generation // You can also return a JSON or a prompt message instructing the AI how to respond to a user // Functions may be synchronous or asynchronous. // // The bot will inject the following parameters: // - parameters: function parameters provided by the AI when the function has parameters defined // - response: AI generated response object, useful to evaluate the AI response and take actions // - data: webhook event context, useful to access the last user message, chat and contact information // - device: WhatsApp number device information provided the by Wassenger API // - messages: an list of previous messages in the same user chat run: async ({ parameters, response, data, device, messages }) => { // console.log('=> data:', response) // console.log('=> response:', response) const reply = [ '*Send & Receive messages + API + Webhooks + Team Chat + Campaigns + CRM + Analytics*', '', '- Platform Professional: 30,000 messages + unlimited inbound messages + 10 campaigns / month', '- Platform Business: 60,000 messages + unlimited inbound messages + 20 campaigns / month', '- Platform Enterprise: unlimited messages + 30 campaigns', '', 'Each plan is limited to one WhatsApp number. You can purchase multiple plans if you have multiple numbers.', '', '*Find more information about the different plan prices and features here:*', 'https://wassenger.com/#pricing' ].join('\n') return reply }, },

// Sample function to load user information from a CRM { name: 'loadUserInformation', description: 'Find user name and email from the CRM', parameters: { type: 'object', properties: {} }, run: async ({ parameters, response, data, device, messages }) => { // You may call an remote API and run a database query const reply = 'I am sorry, I am not able to access the CRM at the moment. Please try again later.' return reply } },

// Sample function to verify the current date and time { name: 'verifyMeetingAvaiability', description: 'Verify if a given date and time is available for a meeting before booking it', parameters: { type: 'object', properties: { date: { type: 'string', format: 'date-time', description: 'Date of the meeting' } }, required: ['date'] }, run: async ({ parameters, response, data, device, messages }) => { console.log('=> verifyMeetingAvaiability call parameters:', parameters) // Example: you can make an API call to verify the date and time availability and return the confirmation or rejection message const date = new Date(parameters.date) if (date.getUTCDay() > 5) { return 'Not available on weekends' } if (date.getHours() < 9 || date.getHours() > 17) { return 'Not available outside business hours: 9 am to 5 pm' } return 'Available' } },

// Sample function to determine the current date and time { name: 'bookSalesMeeting', description: 'Book a sales or demo meeting with the customer on a specific date and time', parameters: { type: 'object', properties: { date: { type: 'string', format: 'date-time', description: 'Date of the meeting' } }, required: ['date'] }, run: async ({ parameters, response, data, device, messages }) => { console.log('=> bookSalesMeeting call parameters:', parameters) // Make an API call to book the meeting and return the confirmation or rejection message return 'Meeting booked successfully. You will receive a confirmation email shortly.' } },

// Sample function to determine the current date and time { name: 'currentDateAndTime', description: 'What is the current date and time', run: async ({ parameters, response, data, device, messages }) => { return new Date().toLocaleString() } } ]

Esegui il bot

Puoi eseguire il programma del bot ora stesso nel tuo browser usando StackBlitz:

WhatsApp ChatGPT-powered Edit descriptio.npr.new

Utilizzo

Esegui il programma del bot:

node main

Esegui il programma del bot su una porta personalizzata:

PORT=80 node main

Esegui il programma del bot per un dispositivo specifico connesso a Wassenger:

DEVICE=WHATSAPP_DEVICE_ID node main

Esegui il programma del bot in modalità produzione:

NODE_ENV=production node main

Esegui il bot con un server webhook esistente senza il tunnel Ngrok:

WEBHOOK_URL=https://bot.company.com:8080/webhook node main

Nota: `https://bot.company.com:8080\` deve puntare al programma del bot in esecuzione sul tuo server ed essere raggiungibile in rete usando HTTPS per una connessione sicura.

Domande

Posso addestrare l'AI a comportarsi in modo personalizzato?

Sì! Puoi fornire istruzioni personalizzate all'AI per determinare il comportamento del bot, l'identità e altro.

Per impostare le tue istruzioni personalizzate, inserisci il testo in `config.js` > `botInstructions`.

Posso istruire l'AI a non rispondere a argomenti non correlati?

Sì! Definendo un insieme di istruzioni chiare ed esplicite, puoi insegnare all'AI di attenersi al ruolo e di rifiutare cortesemente di rispondere a temi non pertinenti.

Ad esempio, puoi aggiungere quanto segue nelle tue istruzioni:

You are a smart virtual customer support assistant who works for Wassenger.
Be polite, be gentle, be helpful and emphatic.
Politely reject any queries that are not related to your customer support role or Wassenger itself.
Strictly stick to your role as customer support virtual assistant for Wassenger.

Posso personalizzare le risposte e il comportamento del chatbot?

Certo! Il codice è disponibile gratuitamente e puoi adattarlo quanto necessario.

Hai solo bisogno di alcune conoscenze di JavaScript/Node.js, e puoi sempre chiedere a ChatGPT di aiutarti a scrivere il codice che ti serve.

Come faccio a impedire al bot di rispondere a determinate chat?

Dovresti semplicemente assegnare le chat specifiche a un agente sulla chat web di Wassenger o usando l'API.

In alternativa, puoi impostare etichette in blacklist nel campo `config.js` > `skipChatWithLabels`, quindi aggiungere una di queste etichette alla chat specifica che vuoi venga ignorata dal bot. Puoi assegnare etichette alle chat usando la chat web di Wassenger o usando l'API.

Devo usare Ngrok?

No, non è necessario. Ngrok è usato solo per scopi di sviluppo/test quando esegui il programma dal tuo computer locale. Se esegui il programma su un server cloud, molto probabilmente non avrai bisogno di Ngrok se il tuo server è raggiungibile via Internet utilizzando un dominio pubblico (es. bot.company.com) o un IP pubblico.

In tal caso, devi fornire l'URL completo del tuo server che termina con `/webhook` come mostrato quando esegui il programma del bot:

WEBHOOK_URL=https://bot.company.com:8080/webhook node main

Nota: `https://bot.company.com:8080\` deve puntare al programma del bot in esecuzione sul tuo server ed essere raggiungibile in rete usando HTTPS per una connessione sicura.

Cosa succede se il programma fallisce?

Controlla l'errore nel terminale e assicurati di eseguire il programma con i permessi sufficienti per avviarlo sulla porta 8080 in localhost.

Come evitare che chat specifiche vengano risposte dal bot?

Per impostazione predefinita, il bot ignorerà i messaggi inviati in chat di gruppo, chat/contatti bloccati e archiviati.

Oltre a ciò, puoi mettere in blacklist o whitelist numeri di telefono specifici e chat con etichette che devono essere gestite dal bot.

Vedi le opzioni `numbersBlacklist`, `numbersWhitelist` e `skipChatWithLabels` in `config.js` per ulteriori informazioni.

Posso eseguire questo bot sul mio server?

Assolutamente! Distribuisci o trasferisci il codice sorgente del programma sul tuo server ed esegui il comando di avvio da lì.

I requisiti sono gli stessi, indipendentemente da dove esegui il bot.

Ricorda anche di definire la variabile d'ambiente `WEBHOOK_URL` con l'URL pubblico accessibile da Internet del tuo server come spiegato prima.

Ready to transform your WhatsApp communication?

Start automating your customer interactions today with Wassenger

Get Started Free