Build a Multilingual Chat App with React.js and Langchain

Creating a chat application that supports multiple languages can be challenging. In this tutorial, we'll show you how to build a multilingual streaming chat application using React.js and Langchain to break language barriers and enhance communication in your app.

Prerequisites

Before diving into the tutorial, make sure you have the following:

  • Basic knowledge of JavaScript and React.js
  • Node.js and NPM installed on your system
  • A code editor (e.g., Visual Studio Code)

Step 1: Set up the project

First, create a new directory for your project and navigate into it:

mkdir multilingual-chat
cd multilingual-chat

Next, initialize a new React project using create-react-app:

npx create-react-app multilingual-chat-app
cd multilingual-chat-app

Step 2: Install dependencies

We'll need a few additional libraries for our chat application. Install them using the following command:

npm install socket.io-client langchain axios

Step 3: Set up the server

Create a new directory called server at the root of your project and navigate into it:

mkdir server
cd server

Initialize a new Node.js project:

npm init -y

Install the required server dependencies:

npm install express socket.io cors

Create a new file called index.js in the server directory and add the following code to set up a simple Express server with Socket.IO:

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, {
  cors: {
    origin: '*',
  },
});

io.on('connection', (socket) => {
  console.log('User connected');

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

const PORT = process.env.PORT || 5000;

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Step 4: Implement the translation functionality

Create a new file called translate.js in the server directory and add the following code:

const axios = require('axios');

async function translateText(text, targetLanguage) {
  const API_KEY = 'your-langchain-api-key';
  const url = `https://translate.langchain.io/translate?api_key=${API_KEY}`;

  try {
    const response = await axios.post(url, {
      text,
      target: targetLanguage,
    });

    return response.data.translatedText;
  } catch (error) {
    console.error('Error translating text:', error);
    return null;
  }
}

module.exports = translateText;

Replace 'your-langchain-api-key' with your actual Langchain API key.

Step 5: Update the server to handle chat messages

Update the index.js file in the server directory with the following code to handle chat messages and translations:

// ...
const translateText = require('./translate');

io.on('connection', (socket) => {
  console.log('User connected');

  // ...

  // Handle chat message
  socket.on('chat message', async (msg, targetLanguage) => {
    const translatedMessage = await translateText(msg, targetLanguage);
    io.emit('chat message', translatedMessage);
  });
});

// ...

Step 6: Create the chat components

Navigate to the src directory in your React app and create a new folder called components. Inside the components folder, create two new files: ChatInput.js and ChatMessages.js.

ChatInput.js

Add the following code to ChatInput.js:

import React, { useState } from 'react';

const ChatInput = ({ onSendMessage }) => {
  const [message, setMessage] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (message.trim()) {
      onSendMessage(message);
      setMessage('');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        placeholder="Type your message here..."
      />
      <button type="submit">Send</button>
    </form>
  );
};

export default ChatInput;

ChatMessages.js

Add the following code to ChatMessages.js:

import React from 'react';

const ChatMessages = ({ messages }) => {
  return (
    <ul>
      {messages.map((message, index) => (
        <li key={index}>{message}</li>
      ))}
    </ul>
  );
};

export default ChatMessages;

Step 7: Update the App component

Update the App.js file in the src directory with the following code:

import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
import ChatInput from './components/ChatInput';
import ChatMessages from './components/ChatMessages';

const socket = io('http://localhost:5000');

function App() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    socket.on('chat message', (message) => {
      setMessages((prevMessages) => [...prevMessages, message]);
    });

    return () => {
      socket.disconnect();
    };
  }, []);

  const handleSendMessage = (message) => {
    socket.emit('chat message', message, 'en'); // Change 'en' to the desired target language
  };

  return (
    <div className="App">
      <h1>Multilingual Chat</h1>
      <ChatMessages messages={messages} />
      <ChatInput onSendMessage={handleSendMessage} />
    </div>
  );
}

export default App;

Step 8: Run the application

Start the server by running the following command in the server directory:

node index.js

Start the React app by running the following command in the multilingual-chat-app directory:

npm start

Your multilingual chat app should now be running on http://localhost:3000. Start chatting and enjoy real-time translations!

Conclusion

In this tutorial, we've built a multilingual streaming chat application using React.js and Langchain. This simple app demonstrates how easy it is to integrate real-time translations into your projects, enhancing communication and breaking language barriers.

An AI coworker, not just a copilot

View VelocityAI