For AI agents: the complete documentation index is available at https://docs.ovhcloud.com/fr/llms.txt, the full documentation bundle is available at https://docs.ovhcloud.com/fr/llms-full.txt, and this page is available as Markdown at https://docs.ovhcloud.com/fr/guides/public-cloud/ai-machine-learning/ai-endpoints-chatbot-langchain-javascript.md.

AI Endpoints - Développer un chatbot en JavaScript avec LangChain

Voir en Markdown

Apprenez à développer un chatbot en utilisant JavaScript, LangChain et AI Endpoints

Info

AI Endpoints est couvert par les Conditions particulières OVHcloud Public Cloud (voir l’Annexe 10 – « Conditions spécifiques – AI Endpoints »).

Introduction

LangChain est un framework de référence pour construire des applications reposant sur des grands modèles de langage (LLM). Bien qu’il soit surtout connu pour Python, LangChain prend également en charge JavaScript/TypeScript — idéal pour les applications frontend et fullstack.

Dans ce tutoriel, nous allons vous montrer comment construire un chatbot en ligne de commande simple à l’aide de LangChain et des AI Endpoints d’OVHcloud, d’abord en mode bloquant, puis avec du streaming pour des réponses en temps réel.

Objectif

Ce tutoriel montre comment :

  • Mettre en place un chatbot Node.js à l’aide de LangChain JS
  • Se connecter à OVHcloud AI Endpoints pour accéder aux LLM
  • Prendre en charge à la fois le mode de réponse standard et le mode streaming

Prérequis

En pratique

Configurer l’environnement

Vous devrez déclarer les variables d’environnement suivantes :

_OVH_AI_ENDPOINTS_ACCESS_TOKEN=<ai-endpoints-api-token>
_OVH_AI_ENDPOINTS_MODEL_NAME=Mistral-7B-Instruct-v0.3 # (or any other model you want to use)
_OVH_AI_ENDPOINTS_URL=https://oai.endpoints.kepler.ai.cloud.ovh.net/v1

Veillez à remplacer la valeur du token (OVH_AI_ENDPOINTS_ACCESS_TOKEN) par la vôtre. Si vous n’en possédez pas encore, suivez les instructions du guide AI Endpoints - Premiers pas.

Configuration du projet

La première étape consiste à récupérer les dépendances nécessaires. Pour cela, créez un fichier package.json avec le contenu suivant :

{
  "name": "js-langchain-chatbot",
  "version": "1.0.0",
  "type": "module",
  "description": "Chatbot example with LangChain and AI Endpoints",
  "main": "chatbot.js",
  "scripts": {
    "start": "node chatbot.js"
  },
  "author": "OVHcloud",
  "license": "Apache-2.0",
  "dependencies": {
    "@langchain/mistralai": "^0.0.22",
    "@langchain/openai": "^0.0.34",
    "commander": "^12.1.0",
    "langchain": "^0.2.2"
  }
}

Puis exécutez :

npm install

Créer le chatbot en mode bloquant

Créez un nouveau fichier nommé chatbot.js et collez-y le code suivant :

import { ChatMistralAI } from "@langchain/mistralai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { Command } from 'commander';

/**
 * Function to do a chat completion request to the LLM given a user question.
 * @param question (String) the question to ask to the LLM.
 */
async function chatCompletion(question) {
  const promptTemplate = ChatPromptTemplate.fromMessages([
    ["system", "You are Nestor, a virtual assistant. Answer to the question."],
    ["human", "{question}"]
  ]);

  // Use gpt-oss-120b as LLM
  const model = new ChatMistralAI({
    modelName: process.env.OVH_AI_ENDPOINTS_MODEL_NAME,
    model: process.env.OVH_AI_ENDPOINTS_MODEL_NAME,
    apiKey: process.env.OVH_AI_ENDPOINTS_ACCESS_TOKEN,
    endpoint: process.env.OVH_AI_ENDPOINTS_URL,
    maxTokens: 1500,
    streaming: false,
    verbose: false,
  });

  // Chain the model to the prompt to "apply it"
  const chain = promptTemplate.pipe(model);
  const response = await chain.invoke({ question: question });
  
  console.log(response.content);
}


/**
 * Main entry of the CLI.
 * Parameter --question is used to pass the question to the LLM.
 **/
const program = new Command();

program
  .option('--question <value>', 'Overwriting value.', '"What is the meaning of life?"')
  .parse(process.argv);

const options = program.opts();
chatCompletion(options.question);

Vous pouvez tester votre nouvel assistant avec la commande suivante :

node chatbot.js --question "What is OVHcloud?"

Ce qui vous donnera une sortie similaire à :

OVHcloud is a global cloud computing company that offers a wide range of services including web hosting, 
virtual private servers, cloud storage, and dedicated servers. 
It was founded in 1999 and is headquartered in Roubaix, France. 
OVHcloud operates its own data centers and network infrastructure, providing services to customers around the world. 
The company offers a variety of cloud solutions, including public, 
private, and hybrid cloud options, as well as dedicated servers, web hosting, and other managed services. 
OVHcloud is known for its high-performance, scalable, and secure cloud infrastructure.

Activer le mode streaming

Comme toujours, vous souhaitez probablement un véritable chatbot avec un style conversationnel. Pour cela, ajoutons une fonctionnalité de streaming avec le code suivant :

import { ChatMistralAI } from "@langchain/mistralai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { Command } from 'commander';
import { setTimeout } from "timers/promises";

/**
 * Function to do a chat completion request to the LLM given a user question.
 * @param question (String) the question to ask to the LLM.
 */
async function chatCompletion(question) {
  const promptTemplate = ChatPromptTemplate.fromMessages([
    ["system", "You are Nestor, a virtual assistant. Answer to the question."],
    ["human", "{question}"]
  ]);

  // Use gpt-oss-120b as LLM
  const model = new ChatMistralAI({
    modelName: process.env.OVH_AI_ENDPOINTS_MODEL_NAME,
    model: process.env.OVH_AI_ENDPOINTS_MODEL_NAME,
    apiKey: process.env.OVH_AI_ENDPOINTS_ACCESS_TOKEN,
    endpoint: process.env.OVH_AI_ENDPOINTS_URL,
    maxTokens: 1500,
    streaming: true,
    verbose: false,
  });

  // Chain the model to the prompt to "apply it"
  const chain = promptTemplate.pipe(model);
  const stream = await chain.stream({ question: question });

  for await (const chunk of stream) {
    // Timeout to simulate a human answering the question
    await setTimeout(150);
    process.stdout.write(chunk.content);
  }
}

/**
 * Main entry of the CLI.
 * Parameter --question is used to pass the question to the LLM.
 **/
const program = new Command();

program
  .option('--question <value>', 'Overwriting value.', '"What is the meaning of life?"')
  .parse(process.argv);

const options = program.opts();
chatCompletion(options.question);

Exécutez votre chatbot en mode streaming avec :

node chatbot-streaming.js --question "What is OVHcloud?"

Vous verrez la réponse de l’assistant apparaître en temps réel ⏳💬

Conclusion

Avec seulement quelques lignes de JavaScript et LangChain, vous disposez désormais d’un chatbot propulsé par les AI Endpoints d’OVHcloud. Vous pouvez facilement basculer entre le mode bloquant et le mode streaming, offrant à vos utilisateurs une expérience de chat réactive.

Aller plus loin

Vous pouvez ensuite construire et déployer une application web dans le cloud, en rendant votre interface accessible à tous. Pour cela, consultez les articles et tutoriels suivants :

Pour une formation ou une assistance technique sur la mise en œuvre de nos solutions, contactez votre commercial ou consultez la page Professional Services pour obtenir un devis et faire analyser votre projet par nos experts.

Votre avis nous intéresse !

N’hésitez pas à nous faire part de vos questions, retours et suggestions concernant AI Endpoints et ses fonctionnalités :

  • Dans le canal #ai-endpoints du serveur Discord OVHcloud, où vous pouvez échanger avec la communauté et les équipes OVHcloud.
Cette page vous a-t-elle aidé ?