Getting Started with LangChain.js: A Hello World Example

Getting Started with LangChain.js: A Hello World Example

LangChain.js is a powerful library that enables seamless interaction with Large Language Models (LLMs) in JavaScript applications. In this guide, we'll walk through building a simple Node.js script and then a React app that integrates LangChain.js with OpenAI to fetch AI-generated jokes.

Step 1: Using LangChain.js in a Simple Node.js Script

If you prefer to use LangChain.js in a standalone Node.js script, follow these steps.

Install Dependencies

npm install @langchain/openai dotenv
        


Create a HelloWorld.js file

// Load environment variables from .env file
require('dotenv').config();

// Import the ChatOpenAI class from the LangChain OpenAI package
const { ChatOpenAI } = require("@langchain/openai");

// Create a new instance of ChatOpenAI with configuration
const chat = new ChatOpenAI({
  // Specify the model to use
  modelName: "gpt-4o-mini",
  // Use the API key from environment variables
  openAIApiKey: process.env.OPENAI_API_KEY
});

// Define an async function to fetch and display a joke
async function getJoke() {
  try {
    // Make an asynchronous call to the chat model asking for a joke
    const result = await chat.invoke("Tell me a joke");
    // Print the joke to the console
    console.log("Joke:", result.content);
  } catch (error) {
    // Log any errors that occur during the process
    console.error("Error:", error);
  }
}

getJoke();

        

I highlighted the three main steps below:



Set Up the .env File

Create a .env file in the same directory as your script:

OPENAI_API_KEY=your_openai_api_key_here
        

Run the Script

node HelloWorld.js
        

You should see a joke printed in your terminal!


Step 2: Create a React App

Let's now set up a new React project. Open your terminal and run:

npx create-react-app langchain-hello-world && cd langchain-hello-world
npm start
        



https://github.com/ranyelhousieny/LangChain_React/tree/step1-react-setup

At this point, you should see the default React welcome screen. Now, let's move on to integrating LangChain.js.



Step 3: Add LangChain.js to the Project

First, install the required LangChain.js package:

npm install @langchain/openai
        

Now, update the App.js file to include the LangChain.js integration:

import { useState } from 'react';
import { ChatOpenAI } from "@langchain/openai";

function App() {
  const [response, setResponse] = useState('');
  const [loading, setLoading] = useState(false);

  const handleAskJoke = async () => {
    try {
      setLoading(true);
      const chat = new ChatOpenAI({
        modelName: "gpt-4",
        openAIApiKey: process.env.REACT_APP_OPENAI_API_KEY
      });
      const result = await chat.invoke("Tell me a joke");
      setResponse(result.content);
    } catch (error) {
      console.error('Error:', error);
      setResponse('Error: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ textAlign: 'center', padding: '50px' }}>
      <h1>LangChain.js Joke Generator</h1>
      <button onClick={handleAskJoke} disabled={loading} style={{ padding: '10px 20px', fontSize: '16px', cursor: loading ? 'wait' : 'pointer', margin: '20px 0' }}>
        {loading ? 'Getting a joke...' : 'Tell me a joke!'}
      </button>
      {response && (
        <div style={{ maxWidth: '600px', margin: '20px auto', padding: '20px', backgroundColor: 'rgba(255,255,255,0.1)', borderRadius: '8px' }}>
          {response}
        </div>
      )}
    </div>
  );
}

export default App;
        



Step 4: Set Up the OpenAI API Key

Create a .env file in the root of your project and add your OpenAI API key:

REACT_APP_OPENAI_API_KEY=your_openai_api_key_here
        

Restart your development server:

npm start
        

Now, open your browser and test the button. If everything is set up correctly, you should see a joke displayed on the screen!




Conclusion

You've successfully built a simple Node.js script and a React app using LangChain.js to interact with OpenAI and generate jokes. This foundational example sets the stage for more advanced LangChain.js applications.

要查看或添加评论,请登录

Rany ElHousieny, PhD???的更多文章