10 Sep 2024

Getting Started with Langchain.js

Hello world, in this post, I'll be creating a simple Node.js program to build a basic Large Language Model (LLM) application. In subsequent posts, I'll delve deeper into developing more advanced applications using LLM.

To begin, let's install the necessary packages.

yarn add langchain @langchain/open-ai

Now that we have installed the necessary packages, we need to set some environment variables to allow the library to access API tokens, although explicit passing is also an option.

OPENAI_API_KEY=your-api-key

Now that we have the groundwork laid out, let's dive into coding. Our first step will be to instantiate the model.

import { ChatOpenAI } from "@langchain/openai";

const model = new ChatOpenAI({ model: "gpt-4" });

We can now define some messages that can be passed to the chat model.

import { HumanMessage, SystemMessage } from "@langchain/core/messages";

const messages = [
  new SystemMessage("Translate the following from English into Italian"),
  new HumanMessage("hi!"),
];

We can now pass this list of messages to the .invoke method.

const aiMessage = await model.invoke(messages)
console.log(aiMessage.content)

Running this will output "ciao!" to the console.

© 2024, Priyansh Rastogi.

Powered by living.so