DEV Community

Cover image for Building AI-powered Applications w/ Javascript using Langchain JS for Beginners
Oyemade Oyemaja
Oyemade Oyemaja

Posted on

Building AI-powered Applications w/ Javascript using Langchain JS for Beginners

AI is here to stay. As developers, it's our responsibility to not only develop applications that help improve the quality of life of the human race but also make sure to do it as quickly as possible by taking advantage of the best technologies around so we can do more with less.

In this tutorial, I will introduce Langchain JS which is a framework that simplifies building AI-powered applications by providing all the components needed to build them in one place.

Langchain works with a myriad of LLMs including OpenAI's GPT, Google's Gemini, HuggingFace, and many more. A complete list can be found here.

Quick start: We will be building an emoji explainer app to help describe the emotions behind an emoji or series of emojis.
For example, if these emojis are inputted πŸ˜‚πŸ€£ we should return something similar to The emojis πŸ˜‚πŸ€£ convey a sense of uncontrollable laughter and joy, often used to express extreme amusement or hilarity.

Some requirements before we can begin, you need node.js installed on your machine if you do not have it installed you can download it here, we would also need an API key from the LLM of choice, this case, we would be using OpenAI. Here is a guide on creating an API key for OpenAI.

To get started:

  • Navigate to your preferred folder of choice, open it in your code editor, and run npm init -y in the terminal. A package.json file would be generated in that folder.

  • Edit the package.json file by adding a type property with a value module to the JSON object. "type": "module",.
    This indicates that the files in the project should be treated as ECMAScript modules (ESM) by default.

  • Run npm i langchain dotenv in the terminal to install the required dependencies.

  • Create two (2) new files in the current folder, one called index.js which would house all our code, and another called .env to store our API key.

  • In our .env file, we need to add our API key. You can do this by typing OPENAI_API_KEY=YOUR_OPEN_AI_KEY_GOES_HERE exactly as shown, replacing YOUR_OPEN_AI_KEY_GOES_HERE with your actual OpenAI key.

  • In our index.js file we would import the following dependencies:

// This imports the OpenAI LLM
import { OpenAI } from "langchain/llms/openai";

// This imports the mechanism that helps create the messages
// called `prompts` we send to the LLM
import { PromptTemplate } from "langchain/prompts";

// This imports the tool called `chains` that helps combine 
// the model and prompts so we can communicate with the LLM
import { LLMChain } from "langchain/chains";

// This helps connect to our .env file
import * as dotenv from "dotenv";
dotenv.config();
Enter fullscreen mode Exit fullscreen mode
const template = `Interpret the emotions conveyed by the following emoji(s): {emojis}. Consider each emoji individually and in combination with others in the series. Apply your knowledge of common emoji usage, cultural contexts, and emotional expressions to provide an insightful interpretation. When analyzing multiple emojis, consider the sequence and combination of the emojis to understand any nuanced emotional narrative or sentiment they may collectively express. Additionally, take into account the following considerations:

Emoji Specificity: Identify each emoji and any specific emotions or ideas it typically represents.
Cultural Context: Acknowledge if certain emojis have unique meanings in specific cultural contexts.
Emotional Range: Recognize if emojis express a range of emotions, from positive to negative or neutral.
Sequential Interpretation: When multiple emojis are used, analyze if the sequence changes the overall emotional message.
Complementary and Contrasting Emotions: Note if emojis complement or contrast each other emotionally.
Common Usage Patterns: Reflect on how these emojis are commonly used in digital communication to infer the underlying emotions.
Sarcasm or Irony Detection: Be aware of the possibility of sarcasm or irony in the use of certain emojis.
Emoji Evolution: Consider any recent changes in how these emojis are used or perceived in digital communication.

Based on these guidelines, in one very short sentence, provide a short interpretation of the emotions conveyed by the inputted emoji(s). `;

const promptTemplate = new PromptTemplate({
  template,
  inputVariables: ["emojis"],
});

// Above we created a template variable that contains our
// detailed instructions for the LLM, we also added a 
// variable {emojis} which would be replaced with the emojis
// passed in at runtime.
// We then create a prompt template from the template and
// input variable.

Enter fullscreen mode Exit fullscreen mode

// We create our model and pass it a `temperature` of 0.5
// The `temperature` represents how creative we want 
// the model to be and it takes values 0.1 - 1.
// A lower temperature (closer to 0.1) makes the model's
// responses more predictable and conservative. On the 
// other hand, a higher temperature (closer to 1) allows for
// more creativity and variation in responses.
const openAIModel = new OpenAI({
  temperature: 0.5,
});

// We then use a chain to combine our LLM with our 
// prompt template
const llmChain = new LLMChain({
  llm: openAIModel,
  prompt: promptTemplate,
});

// We then call the chain to communicate with the LLM
// and pass in the emojis we want to be explained.
// Note that the property name `emojis` below must match the
// variable name in the template earlier created.
const result = await llmChain.call({
  emojis: "πŸ˜‚πŸ€£",
});

// Log result to the console
console.log(result.text);

Enter fullscreen mode Exit fullscreen mode
  • Now we would run node index.js in our terminal. We should then see a result similar to this in our console: The emojis πŸ˜‚πŸ€£ convey a sense of extreme amusement and laughter, possibly indicating that the sender found something very funny.

Keep in mind that each time you run the model, the results might vary slightly. However, the overall meaning and context should remain consistent.

Here is a stackblitz with a demo:

Don't hesitate to ask any questions you have in the comments. I'll make sure to respond as quickly as possible.

Top comments (0)