Node.js & JavaScript Examples
Installation​
npm install axios dotenv
Setup​
Créez un fichier .env:
YODI_API_KEY=your_api_key_here
YODI_BASE_URL=https://admin.yodi.tg/api
Créez yodi-client.js:
const axios = require("axios");
require("dotenv").config();
const client = axios.create({
baseURL: process.env.YODI_BASE_URL,
headers: {
Authorization: `Bearer ${process.env.YODI_API_KEY}`,
"Content-Type": "application/json",
},
});
module.exports = client;
Translation Service​
Traduire du texte​
const client = require("./yodi-client");
async function translateText(text, targetLanguage) {
try {
const response = await client.post("/ai/translate", {
text,
targetLanguage,
});
console.log(" Traduction réussie:");
console.log(`Traduit: ${response.data.data.translatedText}`);
console.log(`Source: ${response.data.data.sourceLanguage} → ${response.data.data.targetLanguage}`);
return response.data.data;
} catch (error) {
console.error(" Erreur:", error.response?.data || error.message);
}
}
// Utilisation
translateText("Bonjour le monde", "fr");
Traduire en plusieurs langues​
async function translateMultiple(text, languages) {
const results = {};
for (const lang of languages) {
try {
const response = await client.post("/ai/translate", {
text,
targetLanguage: lang,
});
results[lang] = response.data.data.translatedText;
} catch (error) {
results[lang] = `Erreur: ${error.message}`;
}
}
return results;
}
// Utilisation
const translations = await translateMultiple("Bienvenue sur YODI", [
"mina",
"ewe",
"tem",
"fr",
]);
console.log(translations);
// Output:
// {
// mina: 'Welkom na YODI',
// ewe: 'Akɔtaba me wo YODI',
// tem: 'Ni ka hĂŁ É–a YODI',
// fr: 'Bienvenue sur YODI'
// }
Text Analysis Service​
Analyser un sentiment​
async function analyzeSentiment(text) {
try {
const response = await client.post("/ai/analyze", {
text,
});
const { sentiment, confidence, entities } = response.data.data;
console.log(" Analyse complétée:");
console.log(
`Sentiment: ${sentiment} (${Math.round(confidence * 100)}%)`,
);
console.log(`Entités trouvées: ${entities ? entities.length : 0}`);
return response.data.data;
} catch (error) {
console.error(" Erreur:", error.response?.data || error.message);
}
}
// Utilisation
analyzeSentiment("Je suis très satisfait du service! C'est incroyable!");
Pipeline d'analyse de feedback​
const fs = require("fs");
async function analyzeFeedbackBatch(feedbacks) {
const results = [];
for (const feedback of feedbacks) {
try {
const analysis = await client.post("/ai/analyze", {
text: feedback,
});
results.push({
feedback,
sentiment: analysis.data.data.sentiment,
confidence: analysis.data.data.confidence,
});
} catch (error) {
console.error(`Erreur pour: ${feedback}`, error.message);
}
}
// Statistiques
const positive = results.filter((r) => r.sentiment === "positive").length;
const negative = results.filter((r) => r.sentiment === "negative").length;
console.log(`\n� Résultats (${results.length} feedbacks):`);
console.log(
` Positifs: ${positive} (${Math.round((positive / results.length) * 100)}%)`,
);
console.log(
` Négatifs: ${negative} (${Math.round((negative / results.length) * 100)}%)`,
);
return results;
}
// Utilisation
const feedbacks = [
"Excellent produit!",
"Mauvaise expérience client",
"C'est ok, pas mal",
"Génial! Je recommande!",
];
analyzeFeedbackBatch(feedbacks);
Text-to-Speech Service​
Générer de l'audio​
const fs = require("fs");
async function generateSpeech(text, voice = "clara", language = "fr") {
try {
const response = await client.post("/ai/tts", {
text,
voice,
language,
});
const audioUrl = response.data.data.audioUrl;
console.log(" Audio généré:", audioUrl);
// Télécharger le fichier audio
const audioResponse = await axios.get(audioUrl, { responseType: "stream" });
const writer = fs.createWriteStream("output.mp3");
audioResponse.data.pipe(writer);
return response.data.data;
} catch (error) {
console.error(" Erreur:", error.response?.data || error.message);
}
}
// Utilisation
generateSpeech(
"Bienvenue sur YODI, votre plateforme d'IA africaine",
"clara",
"fr",
);
Générer du texte de bienvenue multilingue​
async function generateMultilingualWelcome(userName) {
const voices = {
fr: { voice: "clara", text: `Bienvenue ${userName}!` },
ewe: { voice: "marcus", text: `Akɔtaba me ${userName}!` },
mina: { voice: "afiya", text: `Welkom ${userName}!` },
};
for (const [lang, config] of Object.entries(voices)) {
try {
const response = await client.post("/ai/tts", {
text: config.text,
voice: config.voice,
language: lang,
});
console.log(` Audio généré pour ${lang}`);
} catch (error) {
console.error(` Erreur ${lang}:`, error.message);
}
}
}
generateMultilingualWelcome("Ahmed");
Chat Service​
Chat simple​
async function chat(message) {
try {
const response = await client.get("/ai/chat", {
params: { message },
});
console.log(` YODI: ${response.data.data.reply}`);
return response.data.data.reply;
} catch (error) {
console.error(" Erreur:", error.response?.data || error.message);
}
}
// Utilisation
chat("Qu'est-ce que YODI?");
Communication​
Envoyer un SMS​
async function sendSMS(phone, message) {
try {
const response = await client.post("/ai/sms/communication", {
phone,
input: message,
});
console.log(" SMS envoyé:");
console.log(`Message ID: ${response.data.data.messageId}`);
return response.data.data;
} catch (error) {
console.error(" Erreur:", error.response?.data || error.message);
}
}
// Utilisation
sendSMS("+1234567890", "Bienvenue sur YODI! Vérifiez votre email.");
Envoyer un appel vocal​
async function makeVoiceCall(phone, message) {
try {
const response = await client.post("/ai/call/communication", {
phone,
input: message,
});
console.log(" Appel lancé:");
console.log(`Message ID: ${response.data.data.messageId}`);
return response.data.data;
} catch (error) {
console.error(" Erreur:", error.response?.data || error.message);
}
}
// Utilisation
makeVoiceCall(
"+1234567890",
"Bonjour, ceci est un appel automatisé de YODI.",
);
Application Complète​
E-Commerce Order Notification​
class OrderNotificationSystem {
constructor(client) {
this.client = client;
}
async notifyOrderConfirmation(order) {
const { orderId, phone, language = "fr" } = order;
console.log(` Traitement de la commande ${orderId}...`);
// 1. Traduire le message
const messageText = `Commande ${orderId} confirmée!`;
const translation = await this.client.post("/ai/translate", {
text: messageText,
targetLanguage: language,
});
// 2. Envoyer SMS
await this.client.post("/ai/sms/communication", {
phone,
input: `Commande ${orderId} confirmée. Merci!`,
});
console.log(` Notification envoyée pour la commande ${orderId}`);
}
async processOrders(orders) {
for (const order of orders) {
await this.notifyOrderConfirmation(order);
}
}
}
// Utilisation
const orders = [
{
orderId: "ORD001",
phone: "+1234567890",
language: "fr",
},
{
orderId: "ORD002",
phone: "+0987654321",
language: "fr",
},
];
const system = new OrderNotificationSystem(client);
system.processOrders(orders);
Customer Support Bot​
class SupportBot {
constructor(client) {
this.client = client;
}
async handleCustomerMessage(message, customerId) {
// 1. Analyser le message
const analysis = await this.client.post("/ai/analyze", {
text: message,
});
const { sentiment, confidence } = analysis.data.data;
// 2. Répondre en chat
const response = await this.client.get("/ai/chat", {
params: { message },
});
// 3. Si négatif, escalade
if (sentiment === "negative" && confidence > 0.8) {
console.log(` Escalade nécessaire pour le client ${customerId}`);
// Envoyer alerte support par SMS
await this.client.post("/ai/sms/communication", {
phone: "+22890123456",
input: `Client ${customerId}: Sentiment négatif détecté — "${message}"`,
});
}
return response.data.data.reply;
}
}
// Utilisation
const bot = new SupportBot(client);
bot.handleCustomerMessage("Je ne suis pas satisfait du service!", "CUST001");
Gestion des Erreurs & Rate Limiting​
async function retryWithBackoff(fn, maxRetries = 5) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (error.response?.status === 429) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
console.log(`⏳ Rate limité. Attente ${delay}ms...`);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
}
// Utilisation
const result = await retryWithBackoff(() =>
client.post("/ai/translate", {
text: "Bonjour",
targetLanguage: "mina",
}),
);
Dashboard de Monitoring​
async function getUsageStats() {
try {
// Récupérer le plan actuel
const plansResponse = await client.get("/subscription/plans");
const currentPlan = plansResponse.data.data.find((p) => p.active);
console.log(" Statistiques d'utilisation:");
console.log(`Plan: ${currentPlan.name}`);
console.log(`Crédits mensuels: ${currentPlan.monthlyCredits}`);
console.log(`Limite requĂŞtes: ${currentPlan.rateLimit} req/min`);
return currentPlan;
} catch (error) {
console.error(" Erreur:", error.message);
}
}
getUsageStats();
Export des Examples​
Créez examples/index.js:
module.exports = {
translation: require("./translation"),
analysis: require("./analysis"),
tts: require("./tts"),
chat: require("./chat"),
agents: require("./agents"),
};
Utilisez dans votre app:
const examples = require("./examples");
// Translation
await examples.translation.translateText("Hello", "fr");
// Analysis
await examples.analysis.analyzeSentiment("Great service!");
// Chat
await examples.chat.sendMessage("How does YODI work?");