CLI Chatbot with LangChain and OpenAI in Node.js - Robin Wieruch

CLI Chatbot with LangChain and OpenAI in Node.js - Robin Wieruch

Want to build a chatbot in your Node.js terminal using JavaScript? We will walk through the most basic scenario when using LangChain and OpenAI. In this guide, we’ll walk through creating a simple CLI chatbot using Node.js. You’ll learn how to interact with OpenAI’s language model and process user input in a terminal-based interface.

By the end, you’ll have a working chatbot that can answer questions, generate text, and even hold a conversation—right from your terminal!

First, install the necessary dependencies:

And second, to use OpenAI, we need to set up the API key. Sign up for an account at OpenAI and create an API key. Then, set the key as an environment variable:

Now, let’s write the core function that interacts with OpenAI using LangChain. We will create a function to send a message to the chatbot and receive a response:

Here’s what’s happening:

We want users to interact with the chatbot from the command line. To achieve this, we’ll use Node.js’ built-in readline module. See the previous tutorial for a more detailed explanation:

Let’s try it by running the chat function with npm run dev . Now, you should see a prompt asking you to enter a command. Try asking it a question, like:

The chatbot should respond with a helpful answer! Now that you have a working chatbot, here are some ways to improve it:

Congratulations! You’ve built a CLI chatbot using LangChain and OpenAI in Node.js. This is just the beginning—you can expand it with features like memory, API integrations, and even different AI models. Now it’s your turn! Try modifying the chatbot, adding new features, and exploring more capabilities with LangChain.

Recommended articles