Getting Started with LangChain.js: Calling OpenAI to Tell a Joke

Getting Started with LangChain.js: Calling OpenAI to Tell a Joke

Artificial Intelligence is becoming more accessible for frontend developers, thanks to LangChain.js. If you've ever wanted to integrate OpenAI’s GPT models directly into a React app—without needing a backend—this guide is for you!

In this tutorial, we’ll walk through a super simple example: asking OpenAI to tell a joke using LangChain.js.


What is LangChain.js?

LangChain.js is a JavaScript library that makes it easy to interact with Large Language Models (LLMs) like OpenAI’s GPT-4.

Instead of manually crafting API calls to OpenAI, LangChain handles it for us, allowing a more structured way to build AI-powered applications.

?? Why use LangChain?

  • Simplifies API calls: No need to manually send HTTP requests.
  • Works in the browser: No backend required.
  • Future expansion: Easily add memory, tools, or agents later.

Today, we'll use LangChain in a React app to call OpenAI and generate a joke.


Step 1: Set Up a React Project

If you don’t have a React project, create one by running:

npx create-react-app langchain-openai
cd langchain-openai
npm install @langchain/openai langchain
        

This installs LangChain.js, which we’ll use to talk to OpenAI.



Install MUI

npm install @mui/material @emotion/react @emotion/styled        

Step 2: Modify App.js to Use LangChain.js

Replace everything in src/App.js with the following code:

import React, { useState } from "react";
import { Button, TextField, Typography, Container, Box } from "@mui/material";
import { ChatOpenAI } from "@langchain/openai";

function App() {
  const [apiKey, setApiKey] = useState(""); // Stores OpenAI API key
  const [joke, setJoke] = useState(""); // Stores AI-generated joke

  // Handle API key input
  const handleApiKeyChange = (event) => {
    setApiKey(event.target.value);
  };

  // Call OpenAI using LangChain
  const handleTellJoke = async () => {
    if (!apiKey) {
      alert("Please enter your OpenAI API key.");
      return;
    }

    const model = new ChatOpenAI({
      openAIApiKey: apiKey, // Provide the API key
      modelName: "gpt-4", // Choose model
    });

    try {
      const response = await model.invoke([
        { role: "system", content: "You are a funny comedian. Keep jokes clean and family-friendly." },
        { role: "user", content: "Tell me a funny joke." }
      ]);
      setJoke(response.content); // Display the AI-generated joke
    } catch (error) {
      console.error("Error calling OpenAI:", error);
      setJoke("Failed to get a joke. Check API key.");
    }
  };

  return (
    <Container maxWidth="sm" style={{ marginTop: "20px" }}>
      <Typography variant="h4" align="center" gutterBottom>
        LangChain Joke Generator ??
      </Typography>

      {/* API Key Input */}
      <Box marginBottom="20px">
        <Typography variant="h6">OpenAI API Key:</Typography>
        <TextField
          fullWidth
          type="password"
          placeholder="Enter your API key"
          value={apiKey}
          onChange={handleApiKeyChange}
        />
      </Box>

      {/* Joke Button */}
      <Button variant="contained" color="primary" onClick={handleTellJoke} fullWidth>
        Tell Me a Joke
      </Button>

      {/* Display Joke */}
      {joke && (
        <Box marginTop="20px">
          <Typography variant="h6">Generated Joke:</Typography>
          <Typography variant="body1">{joke}</Typography>
        </Box>
      )}
    </Container>
  );
}

export default App;

        





Explaining the Code: LangChain Joke Generator in React

This React application is a simple AI-powered joke generator that interacts with OpenAI’s GPT-4 using LangChain.js. It runs entirely in the browser with no backend required.


1. Imports & Dependencies

import React, { useState } from "react";
import { Button, TextField, Typography, Container, Box } from "@mui/material";
import { ChatOpenAI } from "@langchain/openai";
        


What’s Happening Here?

  • React & useState → Used for state management.
  • Material-UI Components → Used for layout and styling (Button, TextField, Container, etc.).
  • ChatOpenAI from LangChain → A wrapper to interact with OpenAI’s GPT models.


2. State Management

const [apiKey, setApiKey] = useState(""); // Stores OpenAI API key
const [joke, setJoke] = useState(""); // Stores AI-generated joke
        


  • apiKey → Stores the user’s OpenAI API key.
  • joke → Stores the AI-generated joke.


3. Handling User Input

const handleApiKeyChange = (event) => {
  setApiKey(event.target.value);
};
        


  • Updates the apiKey state whenever the user types in the input field.


4. Calling OpenAI Using LangChain

const handleTellJoke = async () => {
  if (!apiKey) {
    alert("Please enter your OpenAI API key.");
    return;
  }

  const model = new ChatOpenAI({
    openAIApiKey: apiKey, // Provide the API key
    modelName: "gpt-4", // Choose model
  });
        


What’s Happening Here?

1?? Checks if an API key is provided.

2?? Creates a ChatOpenAI instance using LangChain.js.

  • openAIApiKey: apiKey → Uses the user's API key.
  • modelName: "gpt-4" → Specifies GPT-4 as the model.


5. Sending a Structured Conversation to OpenAI

try {
  const response = await model.invoke([
    { role: "system", content: "You are a funny comedian. Keep jokes clean and family-friendly." },
    { role: "user", content: "Tell me a funny joke." }
  ]);
  setJoke(response.content); // Display the AI-generated joke
} catch (error) {
  console.error("Error calling OpenAI:", error);
  setJoke("Failed to get a joke. Check API key.");
}
        

This code:

  1. Sends a structured prompt to OpenAI.
  2. Retrieves the AI-generated joke from the response.
  3. Handles errors gracefully, ensuring the UI doesn’t break.

Here is step by step:

Executing the AI Call

const response = await model.invoke([
  { role: "system", content: "You are a funny comedian. Keep jokes clean and family-friendly." },
  { role: "user", content: "Tell me a funny joke." }
]);        

  • model.invoke([...]): This function sends a structured request to OpenAI.
  • Roles in the request:System (role: "system") → Defines how the AI should behave.User (role: "user") → Represents the user’s actual request.
  • Purpose: The AI is asked to behave like a clean, family-friendly comedian and then provide a joke.


Handling the AI’s Response

setJoke(response.content); // Display the AI-generated joke        

  • response.content → Retrieves the AI-generated joke from OpenAI's response.
  • setJoke(...) → Updates the React state so the joke appears in the UI.


Error Handling

} catch (error) {
  console.error("Error calling OpenAI:", error);
  setJoke("Failed to get a joke. Check API key.");
}        

  • Catches any errors if the OpenAI call fails (e.g., incorrect API key, network issues).
  • Logs the error to the browser console.
  • Displays a fallback message instead of a joke if something goes wrong.


6. The User Interface (React JSX)

return (
  <Container maxWidth="sm" style={{ marginTop: "20px" }}>
    <Typography variant="h4" align="center" gutterBottom>
      LangChain Joke Generator ??
    </Typography>
        


  • Container → Centers the content on the page.
  • Typography → Displays the app title.


API Key Input Field

<Box marginBottom="20px">
  <Typography variant="h6">OpenAI API Key:</Typography>
  <TextField
    fullWidth
    type="password"
    placeholder="Enter your API key"
    value={apiKey}
    onChange={handleApiKeyChange}
  />
</Box>
        

  • Users enter their OpenAI API key here.
  • Type is set to password for security.


Joke Button

<Button variant="contained" color="primary" onClick={handleTellJoke} fullWidth>
  Tell Me a Joke
</Button>
        


  • Calls handleTellJoke() when clicked.
  • Requests OpenAI to generate a joke.


Displaying the AI-Generated Joke

{joke && (
  <Box marginTop="20px">
    <Typography variant="h6">Generated Joke:</Typography>
    <Typography variant="body1">{joke}</Typography>
  </Box>
)}
        


  • Joke is displayed only if joke is not empty.
  • Uses Material-UI's Typography for formatting.


7. Exporting the Component

export default App;        

  • Makes App.js the main component of the React app.


How It Works

1?? User enters their OpenAI API key.

2?? Clicks “Tell Me a Joke”.

3?? LangChain sends a structured conversation (system + user prompt).

4?? OpenAI returns a joke.

5?? The joke is displayed on the screen.

? No backend required—everything runs in the browser!


What’s Next?

Now that we’ve called OpenAI from LangChain.js, we can move to Step 2: Prompt Templates

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

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